Avoid rounding in new python string formatting

I want to replace the old string formatting behavior with the new python string formatting syntax in my scripts, but how to avoid rounding when working with float?

Old version

print ('%02d:%02d:%02d' % (0.0,0.9,67.5))

gives 00:00:67

while my (obviously wrong) translation into the new syntax

print ('{0:0>2.0f}:{1:0>2.0f}:{2:0>2.0f}'.format(0.0,0.9,67.5))

gives 00:01:68.

How to avoid rounding here and get old output with new format syntax?

+4
source share
2 answers

Explicitly convert arguments to ints:

>>> '{:02}:{:02}:{:02}'.format(int(0.0), int(0.9), int(67.5))
'00:00:67'

By the way, you do not need to specify an argument index ( {0}, {1}, ..) if you are using Python 2.7+, Python 3.1+ (autonumbering) .

+5
source

"" :

'%d' % 7.7         # truncates to 7
'%.0f' % 7.7       # rounds to 8
format(7.7, 'd')   # refuses to convert
format(7.7, '.0f') # rounds to 7

, float . :

>>> math.trunc(f) # ignore the fractional part
67
>>> math.floor(f) # round down
67
>>> math.ceil(f)  # round up
68
>>> round(f)      # round nearest
68
+1

Source: https://habr.com/ru/post/1526861/


All Articles