CodeFaster

CodeFaster

Share this post

CodeFaster
CodeFaster
Don't serialize money as a float

Don't serialize money as a float

Tyler Adams's avatar
Tyler Adams
Dec 20, 2023
∙ Paid
3

Share this post

CodeFaster
CodeFaster
Don't serialize money as a float
Share

In the US (and afaik all non JPY, KRW currencies), we’re cursed with fractional currencies. We can pay $1.49 for a candy bar. So if we want to represent that in code, the obvious thing is to use floats

x = '1.49'

Great. Right? Right?

CodeFaster is a reader-supported publication. To receive new posts and support my work, consider becoming a free or paid subscriber.

a = '0.10'
b = '0.20'
print(a+b)
# 0.30000000000000004

which is a mess. Floating point is a good system, but it doesn’t optimize for correctness when dealing with only 1/100ths. Instead, we should use integers and use the smallest denomination. Integer math is well understood and makes bugs more obvious.

print(5//3)
# 1

This is done at most leading financial institutions (but not the API I was just reading!). In practice, this is what it looks like:

Monite

Stripe

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Tyler Adams
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share