3

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.

twasbrillig
  • 17,084
  • 9
  • 43
  • 67
i'm PosSible
  • 1,373
  • 2
  • 11
  • 30

2 Answers2

6

You can do this kind of thing

>>> val = 9.68
>>> round(val*20)/20.0
9.6999999999999993
Darth Kotik
  • 2,261
  • 1
  • 20
  • 29
1

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.

Community
  • 1
  • 1
Dunes
  • 37,291
  • 7
  • 81
  • 97