WHat is a good way to format a python decimal like this way?
1.00 --> '1'
1.20 --> '1.2'
1.23 --> '1.23'
1.234 --> '1.23'
1.2345 --> '1.23'
If you have Python 2.6 or newer, use format
:
'{0:.3g}'.format(num)
For Python 2.5 or older:
'%.3g'%(num)
Explanation:
{0}
tells format
to print the first argument -- in this case, num
.
Everything after the colon (:) specifies the format_spec
.
.3
sets the precision to 3.
g
removes insignificant zeros. See
http://en.wikipedia.org/wiki/Printf#fprintf
For example:
tests=[(1.00, '1'),
(1.2, '1.2'),
(1.23, '1.23'),
(1.234, '1.23'),
(1.2345, '1.23')]
for num, answer in tests:
result = '{0:.3g}'.format(num)
if result != answer:
print('Error: {0} --> {1} != {2}'.format(num, result, answer))
exit()
else:
print('{0} --> {1}'.format(num,result))
yields
1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
Using Python 3.6 or newer, you could use f-strings
:
In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'