Here is an example:
>>> "%.2f" % 0.355
'0.35'
>>> "%.2f" % (float('0.00355') *100)
'0.36'
Why they give different result?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With