Home > Software design >  Python - limit the number of padding 0s added to float
Python - limit the number of padding 0s added to float

Time:08-05

How can I format a floating point number such that I limit the number of decimal places to a fixed length, but do not add padding zeros in the case when the number has less decimal places than asked for?

For printing with fixed precision, I would usually do the following:

print('{:.3f}'.format(123.4567)) # prints 123.457

However for number with less than 3 decimals, it adds padding zeros:

print('{:.3f}'.format(123.4)) # prints 123.400

What I would like is to have the second version keep the argument unchanged:

print('{:.3f}'.other_format(123.4)) # should print 123.4

What is a possible method to have the number printed as in the third example?

Thank you!

CodePudding user response:

Just do it like this (round will cut additional zeros):

print(round(123.4, 3))

CodePudding user response:

It stupid but answers the question

print('{:.3f}'.format(123.4)[:-2]) # should print 123.4
  • Related