July 05, 2020

Working With Currency in JavaScript

IEEE-754 Floating Points

One client needed me to simply add two products together displaying the total for a new feature to "add both to cart"... not so simple of a task. When it comes to floating point values, JavaScript isn't so great at math. Just as as quick example:

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.

Solution: Convert Floats Into Integers

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

So now we have our ideal total to display to the user. Like I said, I'm pretty nervous about JavaScript handling totals for me so this is why I applied 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:

Copyright © 2020. Jake Birkes