0
hours = "40"
hourrate = "$45.07 "

I write the code :

salary = float(hours)*float(hourrate[1:-1])*52.0

why the result on my terminal is 93745.59999999999? (I was handling a .csv file in python)

Hongli Bu
  • 143
  • 2
  • 8
  • Possible duplicate of [Why not use Double or Float to represent currency?](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) – Arya McCarthy Oct 01 '17 at 02:51
  • Possible duplicate of [How to avoid floating point errors?](https://stackoverflow.com/questions/19473770/how-to-avoid-floating-point-errors) – skrx Oct 01 '17 at 11:01

1 Answers1

0

IEEE

Floating-point is imprecise. 0.1 + 0.2 != 0.3. If you need precision, look into using symbolic mathematics like the sympy module.

hyper-neutrino
  • 5,272
  • 2
  • 29
  • 50
  • @HongliBu Yes, because floating-point cannot always be represented precisely by binary, so I-triple-E tries to fix it but it doesn't always work – hyper-neutrino Oct 01 '17 at 02:54
  • So what's the method in python to solve this problem in float multiplication? use "round()" function? – Hongli Bu Oct 01 '17 at 02:57
  • @HongliBu For currency, you could round to the nearest 1/100, but I'd look into precise symbolic maths for larger scale projects. – hyper-neutrino Oct 01 '17 at 02:58
  • but why some other operations, like float("34.23")*float("24.5") * 52.0, are operated correctly? – Hongli Bu Oct 01 '17 at 03:01
  • @HongliBu because those numbers happen to be precise enough in binary that the slight discrepancy is corrected rather than amplified with some other cases – hyper-neutrino Oct 01 '17 at 03:02