Hollyleaf25
Hollyleaf25

Reputation: 21

How to solve representation errors with floating-point numbers in Python?

I need to truncate a decimal at the hundredths place without rounding. I'm using the the method:

y = 78.459

x = int(y * 100) / 100

which comes back as 78.45. As it should.

However, if I do

y = 5.10

x = int(y * 100) / 100

it come back as 5.09, when it should be 5.10

I know that this is a representation error, due to the floating-point inaccuracies in Python, but I don't know how to fix it. If anyone can either help me figure out how to fix representation errors or maybe find a better way to truncate at the hundredths place, I would really appreciate it. Thanks

Upvotes: 1

Views: 937

Answers (2)

Simon Byrne
Simon Byrne

Reputation: 7874

You can use the quantize function in the decimal module:

>>> import decimal
>>> y = decimal.Decimal('78.459')
>>> z = decimal.Decimal('.01')
>>> y.quantize(z, rounding=decimal.ROUND_DOWN)
Decimal('78.45')

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

Use decimal module for this:

>>> from decimal import Decimal as d
>>> y = d('5.10')
>>> x = int(y * 100) / 100
>>> x
5.1
>>> 

Upvotes: 1

Related Questions