-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnumber_format.py
46 lines (37 loc) · 1.47 KB
/
number_format.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from decimal import Decimal
def number_format(value, decimal_separator=',', mille_separator=None, significance=2):
"""Format a integer or decimal number like PHP number_format function.
Args:
value: The value to be formatted. If its not a valid number, ValueError
will be rised
decimal_separator: The string to use to split decimal places
mille_separator: If specified, milles will be splitted with this string
significance: Number of decimal places
Returns:
A string with the value formatted
Raises:
ValueError: If `value` is not a valid number
"""
if not type(value) in [int, float, Decimal]:
try:
value = float(value)
except ValueError:
raise ValueError('%s is not a number' % value)
# convert to string
format_string = '.%df' % significance
value = format(value, format_string)
# split decimal part
integer, decimal = value.split('.')
if mille_separator:
final_value = []
# add mille_separator to integer part (reverse integer part slicing string)
count = 0
for number in integer[::-1]:
if count > 0 and count % 3 == 0:
final_value.append(mille_separator)
final_value.append(number)
count += 1
final_value = ''.join(reversed(final_value))
else:
final_value = integer
return '%s%s%s' % (final_value, decimal_separator, decimal)