-1

I wrote a small piece of code that rounds a number to the closest multiple of 0.005 but it produces a weird output, that I didn't expect. I am using Python version 3.7.3

Here is the code:

number = 1.639
print(5 * round(number / 5, 3))

Output

1.6400000000000001

Expected output

1.64

Check this replit for detailed output on different values.

Can anyone tell me why this happens?

Radwan Abu-Odeh
  • 1,897
  • 9
  • 16

2 Answers2

1
print(round(5 * round(1.639 / 5, 3), 3))

Round it again since according to what I see you are multiplying the rounded number by 5 then you expect that the number to be rounded. I guess you should round the output of the first rounding step!

ksa
  • 118
  • 8
1

If you want to do the multiplication on the rounding number, here is how you can do:

number = 1.639
temp = round(number / 5, 3)
final = round(5 * temp, 3)

print(final) # 1.64

If you just want to round the final result, here is how you can do it:

number = 1.639
final = round(5 * (number / 5), 3)
print(final) # 1.639
codrelphi
  • 1,075
  • 1
  • 7
  • 13