Suffixation of decimal numbers: Difference between revisions

Added Python example
(Added Python example)
Line 1,047:
1122334455 , 666 : Invalid suffix
10 : 10
</pre>
 
=={{header|Python}}==
{{works with|cpython|3.7.3}}
Tested in Python 3.7.3
<lang python>
import math
import os
 
 
def suffize(num, digits=None, base=10):
prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'X', 'W', 'V', 'U', 'googol']
 
exponent_distance = 10 if base == 2 else 3
num = num.strip().replace(',', '')
num_sign = num[0] if num[0] in '+-' else None
exponent_delineator = [char for char in 'Ee' if char in num]
 
if exponent_delineator:
num_arr = num.split(exponent_delineator[0])
num_arr = [abs(float(i)) for i in num_arr]
num = num_arr[0] * base ** num_arr[1]
else:
num = abs(float(num))
 
if base == 10 and num >= 1e100:
prefix_index = 13
num /= 1e100
else:
if num > 1:
magnitude = math.floor(math.log(num, base))
prefix_index = min(math.floor(magnitude / exponent_distance), 12)
else:
prefix_index = 0
 
num /= base ** (exponent_distance * prefix_index)
 
if digits is not None:
num_str = f'{{:.{digits}f}}'.format(num)
else:
num_str = '{:.3f}'.format(num).strip('0').strip('.')
 
return (num_sign if num_sign else '') + num_str + prefixes[prefix_index] + ('i' if base == 2 else '')
 
 
tests = [('87,654,321',),
('-998,877,665,544,332,211,000', 3),
('+112,233', 0),
('16,777,216', 1),
('456,789,100,000,000', 2),
('456,789,100,000,000', 2, 10),
('456,789,100,000,000', 5, 2),
('456,789,100,000.000e+00', 0, 10),
('+16777216', None, 2),
('1.2e101',)]
 
for test in tests:
print(' '.join(str(i) for i in test if i is not None) + ' : ' + suffize(*test))
</lang>
 
{{out}}
<pre>
87,654,321 : 87.654M
-998,877,665,544,332,211,000 3 : -998.878E
+112,233 0 : +112K
16,777,216 1 : 16.8M
456,789,100,000,000 2 : 456.79T
456,789,100,000,000 2 10 : 456.79T
456,789,100,000,000 5 2 : 415.44727Ti
456,789,100,000.000e+00 0 10 : 457G
+16777216 2 : +16Mi
1.2e101 : 12googol
</pre>