views:

1055

answers:

5

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?

+8  A: 

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".

Jarret Hardie
and for Python3: format(315.153321, ".2f")
NicDumZ
Interestingly, I read yesterday that Python 3.1rc1 now chooses the shortest string representation that resolves to the same floating point number, so your second example with round() would print 315.15 as expected: http://docs.python.org/dev/py3k/whatsnew/3.1.html#other-language-changes
Greg Hewgill
Thank you, Greg - I didn't know that. Good additional info; the more I hear about py3k, the more I can't wait to use it day-to-day!
Jarret Hardie
Ditto to NicDumZ's comment.
Jarret Hardie
+2  A: 

If you just want to display it shortened, you can use the "%f" formating flag:

value = 315.123123123
print "Value is: %.2f" % value

If you want to really cut off the "additional" digits, do something like:

from math import trunc
value = trunc(value*100)/100
sth
You should multiply by 100 inside the parentheses and divide after truncating, otherwise you only get 300 back.
Joey
@Johannes: You're absolutely right...
sth
And then there's the builtin round()…
ΤΖΩΤΖΙΟΥ
+1  A: 

Built-in function round():

>>> num = 315.1532153132
>>> round(num, 2)
3.1499999999999998
Triptych
+1  A: 

You have several options - you can round the number using round(), however this can introduce some inaccuracies (315.15 might round to 315.150000003 for example). If you're just looking to truncate the value of the float when you're displaying it, you can specify the width of the output using printf("%.2f", mynumber). This is probably a better solution, since without knowing more about your specific application it's a good idea in general to keep the entire length of the number for calculation.

Zxaos
+4  A: 

If you're working with currency amounts, I strongly recommend that you use Python's decimal class instead: http://docs.python.org/library/decimal.html

Dave