1

I have a changing variable that is a floating point (ex: 2.003)

And I want to automatically change it to only 2 decimal places.

2

1 Answer 1

11

You can use the round function:

print round(2.003, 2)   # 2.0
print round(2.013, 2)   # 2.01

Otherwise keep the precision and only display the number of decimals you want:

print '%.2f' % 2.003    # 2.00
print '%.2f' % 2.013    # 2.01
2
  • In my experience, the two-argument form of round is very rarely the right thing: if the user is rounding for display purposes, then he/she should be using string formatting (as you describe). If the user wants a float because the output will be used for further computation, you have to wonder why it's acceptable to throw out extra accuracy by rounding. And for monetary applications, Decimal is usually the way to go: with binary floating-point, rounding of (binary approximations to) decimal halfway cases, while perfectly well-defined, is essentially arbitrary from a user's point of view. Aug 7, 2014 at 18:22
  • See mail.python.org/pipermail/python-ideas/2012-September/… and the surrounding thread for more ... Aug 7, 2014 at 18:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.