Menu

1 / 2

int(19.99 * 100) is 1998: why I'd keep prices as integer ticks

DEV Community: cpp·Academic Quant·about 8 hours ago
#E4C9PiZ1
#devtocpp#devto#dev#price#double
Long article (523 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.