-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
92 lines (71 loc) · 2.86 KB
/
script.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from collections import deque
import typing
def number_comma_separation(val: typing.Union[int, float, str]) -> str:
"""
This function will convert an integer or float or string (positive or
negative) into a Indian style comma separated number.
Example
=======
123456789 will be returned as '12,34,56,789'
12.123 will be returned as '12.123'
'123' will be returned as '123'
-12475 will be returned as '-12,475'
-12345.123 will be returned as '-12,345.123'
Parameters
==========
val: an integer or float or string
Returns
=======
a string
"""
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# data type checks
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
error = f'{val} is not a valid format. Acceptable formats are either int ' \
f'or float or string'
assert isinstance(val, int) | isinstance(val, float) | \
isinstance(val, str), error
assert not isinstance(val, bool), error
try:
float(val)
except ValueError as _:
print(f'ERROR: {val} is not a valid number')
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Split the value into two (before and after decimal)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Converting the value to string
val = str(val)
# is the number negative
is_neg, abs_val = (True, val.replace('-', '')) if '-' in val \
else (False, val)
# splitting into two: before and after decimal portions
bf_dec, af_dec = abs_val.split('.') if '.' in abs_val \
else (abs_val, None)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Append commas
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# If the length is <=3, return as is
# Else, first cut the last three characters
# On the rest, run a loop to cut the last two characters at a time
if len(bf_dec) > 3:
csn = deque()
csn.append(bf_dec[-3:])
bf_dec = bf_dec[:-3]
while True:
if len(bf_dec) > 2:
csn.appendleft(bf_dec[-2:])
bf_dec = bf_dec[:-2]
else:
csn.appendleft(bf_dec)
break
csn = ','.join(csn)
else:
csn = bf_dec
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Append '-' (negative) and decimal parts
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Appending '-' if the original value was a negative number
csn = '-' + csn if is_neg else csn
# Appending the decimal part
csn = '.'.join([csn, af_dec]) if af_dec else csn
return csn