4

I want to replace the old string formatting behaviour with the new python string formatting syntax in my scripts, but how to avoid rounding when I deal with floats?

The old version

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

yields 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))

yields 00:01:68.

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

1

2 Answers 2

5

Explicitly convert the arguments to ints:

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

BTW, you don't need to specify argument index ({0}, {1}, ..) if you use Python 2.7+, Python 3.1+ (autonumbering).

Sign up to request clarification or add additional context in comments.

1 Comment

Oops, you are explicitly converting to int :( I thought that format has a way to truncate the decimal part.
2

The "rules" are simple:

'%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 9

To have complete control over the presentation, you can pre-convert the float to an integer. There are several ways to do that depending on your needs:

>>> 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 Comment

format(7.7, '.0f') rounds to 8 and not 7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.