12.99 + 11.00 > 23.990000000000002
This is because of the IEEE Standard for Floating-Point Arithmetic. I ended up down this rabbit hole to better understand it, but ultimately I decided to work around it.
I had a few attempts before I got to this, but so far this is the safest way I'm aware of.
Math.ceil() can also be used to round up in case I accidentally display a discounted price as well to be safe.
((productOnePrice + productTwoPrice) * 100 / 100).toFixed(2); // > ####.##
So to break this down, I first needed these to be whole numbers.
let productOnePrice = 12.99; let productTwoPrice = 11; productOnePrice + productTwoPrice > 23.990000000000002 var total = productOnePrice * 100 + productTwoPrice * 100; > 2399
So far it's been added correctly and if we divide by 100 again it will be fine.
total / 100 > 23.99
However! What if there were zeros in place of .99?
let productOnePrice = 1.1; let productTwoPrice = 2.2; var total = (productOnePrice * 100 + productTwoPrice * 100) / 100; > 3.3
This doesn't work because it needs to be set to the hundredths place. This is why
toFixed is used. At first I tried using
toPrecision, but it wasn't as well as I needed it to be.
var total = ((productOnePrice * 100 + productTwoPrice * 100) / 100).toFixed(2); // hundredths place > 3.30
ceil. It's not needed, but I don't want to give a 'Karen' any reason to yell at my client over a few cents. It's more ideal if an API can provide this total for me without having to do this, but ya know... I would also recommend storing everything as whole numbers
1299 and converting by dividing by 100, using
toFixed when a price needs to be shown.
If you're wanting to see how IEEE-754 works, here are the following resources: