Finance applications demand an integer type due to security reasons. Rounding errors are not acceptable in that kind of application and can lead to exploits. Since JavaScript doesn't offer a proper Integer type, only IEEE 754 Doubles, how do you deal with monetary values in JavaScript, while keeping it safe?
Asked
Active
Viewed 93 times
0
-
You could put it in a string. – steel Jan 23 '15 at 03:47
-
Related question http://stackoverflow.com/questions/2876536/precise-financial-calculation-in-javascript-what-are-the-gotchas. You can store and manipulate all numbers as cents rather than dollars so there are no decimals in use and all addition and subtraction will be precise. – jfriend00 Jan 23 '15 at 04:22
1 Answers
2
IEEE 754 64-bit binary floating point can represent exactly every integer with magnitude no greater than 2^53. That means you can represent exactly, as an integer number of cents, every money amount with magnitude no greater than $90,071,992,547,409.92. For comparison, the US National Debt is currently about $16,787,451,118,147.

Patricia Shanahan
- 25,849
- 4
- 38
- 75
-
Actually it's a penny less, (2^53 - 1). Number.MAX_SAFE_INTEGER may help (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER). – wool.in.silver Jan 27 '16 at 14:30
-
@wool.in.silver **All** powers of two whose magnitude fits in the normal range, including 2^53, are exactly representable. JavaScript's Number.MAX_SAFE_INTEGER imposes an additional requirement that adding one results in a bigger value. Adding one to 2^53 rounds to 2^53. – Patricia Shanahan Jan 27 '16 at 15:28