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.

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
BenFire
  • 519
  • 1
  • 4
  • 7
  • have a look at this previous SO question: http://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly – jbutler483 Aug 07 '14 at 12:37
  • 3
    In calculations, or just for display? Have you looked at [`round`](https://docs.python.org/2/library/functions.html#round)? – jonrsharpe Aug 07 '14 at 12:37

1 Answers1

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
enrico.bacis
  • 27,413
  • 7
  • 76
  • 108
  • 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. – Mark Dickinson Aug 07 '14 at 18:22
  • See https://mail.python.org/pipermail/python-ideas/2012-September/016213.html and the surrounding thread for more ... – Mark Dickinson Aug 07 '14 at 18:27