1

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

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Check this out: https://stackoverflow.com/questions/11522933/python-floating-point-arbitrary-precision-available – Trauer Sep 18 '18 at 01:20

2 Answers2

1

Use decimal module for this:

>>> from decimal import Decimal as d
>>> y = d('5.10')
>>> x = int(y * 100) / 100
>>> x
5.1
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

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')
Simon Byrne
  • 7,694
  • 1
  • 26
  • 50