Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round down to 5 factor value in float value

Tags:

python

I want to convert a float value to round down 5 factor value, this means for example 0.05,0.10,0.15.

Suppose I have a value like 9.48, and I want to convert it into 9.45.

I tried with this:

val = 9.48
val - val % 0.05

It returns 9.450000000000001. That is good for me but the problem is when I have 9.60, it converts asn to 9.55.

When the value is in already factor of 5 then it stays as it is.

like image 585
i'm PosSible Avatar asked May 19 '26 04:05

i'm PosSible


2 Answers

You can do this kind of thing

>>> val = 9.68
>>> round(val*20)/20.0
9.6999999999999993
like image 108
Darth Kotik Avatar answered May 20 '26 18:05

Darth Kotik


This is a result of how floating point numbers are represented -- floats cannot precisely represent 9.60. The closest (64-bit) float to 9.6 is just slightly less 9.6, which is why the operation rounds down. If you need your mathematical operations to be precise then you should be using the decimal module rather than a float.

eg.

val = decimal.Decimal("9.60")
val - val % decimal.Decimal("0.05")

See https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html for an in depth explanation of floating point mathematics.

like image 25
Dunes Avatar answered May 20 '26 19:05

Dunes