python truncate after a hundreds?

ryan picture ryan · Jun 9, 2009 · Viewed 35.2k times · Source

How can truncate an input like 315.15321531321 I want to truncate all the values after the hundredths position so it becomes 315.15

how do i do that?

Answer

Jarret Hardie picture Jarret Hardie · Jun 9, 2009

String formatting under python 2.x should do it for you:

>>> print '%.2f' % 315.15321531321
315.15

This limits the string representation to just 2 decimal places. Note that if you use round(315.153215, 2), you'll end up with another float value, which is naturally imprecise (or overprecise, depending on how you look at it):

>>> round(315.15321531321, 2)
315.14999999999998

Technically, round() is correct, but it doesn't "truncate" the results as you requested at 315.15. In addition, if you round a value like 315.157, it will produce something closer to 315.16... not sure if that's what you mean by "truncate".