Reputation: 141
I need to round values to exactly 2 decimals, but when I use round() it doesn't work, if the value is 0.4, but I need 0.40.
round(0.4232323, 2) = 0.42
bad: round(0.4, 2) = 0.4
How can I solve this?
Upvotes: 1
Views: 3445
Reputation: 47749
If you represent these values as floats then there is no difference between 0.4
and 0.40
. To print them with different precision is just a question of format strings (as per the other two answers).
However, if you want to work with decimals, there is a decimal
module in Python.
>>> from decimal import Decimal
>>> a = Decimal("0.40")
>>> b = Decimal("0.4")
# They have equal values
>>> a == b
True
# But maintain their precision
>>> a + 1
Decimal('1.40')
>>> b + 1
Decimal('1.4')
>>> a - b
Decimal('0.00')
Use the quantize
method to round to a particular number of places. For example:
>>> c = Decimal(0.4232323)
>>> c.quantize(Decimal("0.00"))
Decimal('0.42')
>>> str(c.quantize(Decimal("0.00")))
'0.42'
Upvotes: 1
Reputation: 179717
0.4 and 0.40 are mathematically equivalent.
If you want to display them with two decimal places, use {:.2f}
formatting:
>>> '{:.2f}'.format(0.4)
'0.40'
Upvotes: 7