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
//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'
All examples assume Python 3+
See the difference between truncating and rounding a number
All examples can be viewed on this jupyter notebook
Format float as integer
In other words, round it up to the nearest integer and format:
print['{:.0f}'.format[8.0]]
# >>> '8'
print['{:.0f}'.format[8.9]]
# >>> '9'
Round float to 2 decimal places
print['{:.2f}'.format[5.39120]]
# >>> '5.40'
Format float as percentage
Format a number as a percentage, with 2 decimal places
'{:.2f}%'.format[10.12345]
# >>> '10.12%'
Truncate float at 2 decimal places
View the full code for a generalized version on this notebook
Drop digits after the second decimal place [if there are any].
import re
# see the notebook for a generalized version
def truncate[num]:
return re.sub[r'^[\d+\.\d{,2}]\d*$',r'\1',str[num]]
truncate[8.499]
# >>> '8.49'
truncate[8.49]
# >>> '8.49'
truncate[8.4]
# >>> '8.4'
truncate[8.0]
# >>> '8.0'
truncate[8]
# >>> '8'
Left padding with zeros
Example make the full size equal to 9 [all included], filling with zeros to the left:
# make the total string size AT LEAST 9 [including digits and points], fill with zeros to the left
'{:0>9}'.format[3.499]
# >>> '00003.499'
# make the total string size AT LEAST 2 [all included], fill with zeros to the left
'{:0>2}'.format[3]
# >>> '03'
Right padding with zeros
Example make the full size equal to 11, filling with zeros to the right:
'{: