0

I wish to take in a float variable, e.g.

w = float(1.678)

and control how far out the float goes without round(), e.g.

x = 1.67        
y = 1.6
z = 1

Which was already answered in Python setting Decimal Place range without rounding? and it worked well until one day this number 0.00225 popped up and it some how just doesn't work for this specific number

In [161]: truncate(0.00225, 5)
Out[161]: 0.00224

0.00224 and 0.00226 also gave similar issues.

Here's the output I got while testing from 0.00223 - 0.00227

In [159]: truncate(0.00223, 5)
Out[159]: 0.00223

In [160]: truncate(0.00224, 5)
Out[160]: 0.00223

In [161]: truncate(0.00225, 5)
Out[161]: 0.00224

In [162]: truncate(0.00226, 5)
Out[162]: 0.00225

In [163]: truncate(0.00227, 5)
Out[163]: 0.00227

Why does this happen for some numbers and how do I fix it?

(I mainly use this for a trading algo which requires inputs to have precise decimals)

Jimmy
  • 17
  • 5

1 Answers1

0

This is not a simple problem and it has no simple solution. I would start by studying this article:

https://realpython.com/python-rounding/