Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python2.4.3: format bug?

Here is an example:

>>> "%.2f" % 0.355
'0.35'
>>> "%.2f" % (float('0.00355') *100)
'0.36'

Why they give different result?

like image 494
Anthony Kong Avatar asked Dec 21 '22 18:12

Anthony Kong


1 Answers

This isn't a format bug. This is just floating point arithmetic. Look at the values underlaying your format commands:

In [18]: float('0.00355')
Out[18]: 0.0035500000000000002

In [19]: float('0.00355')*100
Out[19]: 0.35500000000000004

In [20]: 0.355
Out[20]: 0.35499999999999998

The two expressions create different values.

I don't know if it's available in 2.4 but you can use the decimal module to make this work:

>>> import decimal
>>> "%.2f" % (decimal.Decimal('0.00355')*100)
'0.35'

The decimal module treats floats as strings to keep arbitrary precision.

like image 140
aaronasterling Avatar answered Jan 05 '23 06:01

aaronasterling