round/float question
Hans Nowak
hans at zephyrfalcon.org
Fri Oct 10 15:10:11 EDT 2003
Jason Tesser wrote:
> I am using Rekall which uses Python as it's scripting language and I have a question about Python. I am developing a POS system and am working on
> the checkout form. I pass a parameter named SaleID and another one named Total. I am trying to take total and convert it to a float with 2 decimals top be used as money obviously. What would be the proper syntax for this? I tried Total = round(Total [, 2]) i also tried that with float.
round() works fine:
>>> x = 1.2345678
>>> round(x, 2)
1.23
>>>
However, issues with floating point representation might show a different
result. (The tutorial has a section that explains this in detail.)
>>> x = 3.141592
>>> round(x, 2)
3.1400000000000001
>>>
If that is the problem, use str():
>>> y = round(x, 2)
>>> y
3.1400000000000001
>>> str(y), repr(y)
('3.14', '3.1400000000000001')
>>>
Or use a format string to display the float in the format you want:
>>> "%.2f" % (x,)
'3.14'
>>>
HTH,
--
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/
More information about the Python-list
mailing list