If you type int(19.99 * 100) into Python you'll get 1998. I wanted to know how often that happens, so I went through every price from 0.01 to 100.00, multiplied it by 100 and truncated it, and 573 of those 10,000 prices came out a cent short. The first few are 0.29, 0.57, 0.58, 1.13, 1.14 and 1.15, so you don't have to go very far before you meet one.
bad = [ c for c in range ( 1 , 10001 ) if int ( float ( f "{c/100:.2f}" ) * 100 ) != c ] print ( len ( bad ) ) # 573
Enter fullscreen mode
Exit fullscreen mode
It's because 19.99 can't be written exactly in binary, and when you multiply what's stored by 100 you get 1998.9999999999998, which truncation then takes down to 1998. If you change int to round all 10,000 of them come out right, so that's what I'd do at the point where a decimal price comes into the program (a cast in C++ truncates as well, and there I'd use std::llround ).
Comparing prices
You can also get caught when you compare two prices.…