7th
Dealing with currency in Javascript
I probably don’t need to tell you that it’s a very bad idea to do any floating point arithmetic in Javascript. There’s no arbitrary precision decimal library (like BigDecimal). If you have attempted it, you know that this ends very, very badly.
So what’s a dev to do when you need to do some simple arithmetic (adding, subtracting etc) on the client-side?
The answer is to represent your currency amounts as an integral number of cents and use integer arithmetic. Here’s a couple of utility functions that might help:
A word of warning: you could call formatAsCurrency() on a floating point number, but this won’t give you the results you want. So make sure you only call it on Integers only. There’s still limitations on very large integers, but for most purposes this should work just fine.