Never Use Floats for Money (2016)
husobee.github.io
Never Use Floats for Money (2016)
1–10 of 41 posts
Re: Never Use Floats for Money (2016)
#2https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft...
Re: Never Use Floats for Money (2016)
#3Ran into it more recently when doing cryptocurrency market analytics. Bitcoin represents currency as integer numbers of satoshi, where 100M satoshi = 1 BTC. Ethereum represents it as integer numbers of wei, where 10^18 wei = 1 ETH. I thought I'd be smart and use these fundamental units internally, only to find out that basically every exchange quotes prices in floats. By the time you get the data, it's already lost whatever precision it had, and you're just introducing needless friction by trying to get smart.
Sometimes being compatible is more important than being correct.
Re: Never Use Floats for Money (2016)
#4Re: Never Use Floats for Money (2016)
#5Re: Never Use Floats for Money (2016)
#6I used to evangelize integer cents but then I worked on a few systems with floats and the world didn't fall over.
Re: Never Use Floats for Money (2016)
#7Whether or not floating point numbers can be used depends on the context. If you are talking about an accounting system, core banking system, ERP, or similar transactional systems, then sure you probably should use integers not floats.
However, if you're working on any financial model, like something as simple as discounted cash-flow model, then floating point is the correct choice and only choice.
I've had a programmer try to convince me that I had to use integers in financial modeling software that I was developing, and he used this same folksy argument with me. It was a genuine struggle to convince him that this was not a universal law and made no sense for the application at hand.
Re: Never Use Floats for Money (2016)
#8Re: Never Use Floats for Money (2016)
#9The article is right, you should use integers for the number of cents (or whatever the smallest unit of the currency is). That is easy enough as long as you are just adding and subtracting, but what do you do about multiplication and division? How do you calculate interest or yearly yields? I think the answer is fixed point, but that is not easy.
Re: Never Use Floats for Money (2016)
#10I think if you're doing financial modeling, or anything where the real uncertainty is bigger than your unit of money, then it's like any other calculation -- use floats with all of the cautions that you learned in numerical analysis class.
My dad played the stock market and used a slide rule for his calculations.
Another reminiscence: Since he owned some stocks, my dad got annual reports. I remember leafing through the report from General Motors, and seeing that all of the numbers were given at full precision, down to the penny. I remember thinking to myself: If one worker accidentally carries a pencil home, those numbers are all wrong!