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?
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?
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".
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
Built-in function round()
:
>>> num = 315.1532153132
>>> round(num, 2)
3.1499999999999998
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.
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