From what I have read, numbers in JavaScript are actually stored as floating points and there is no real integer type. Is this accurate?
If there is no integer type, then how can I accurately store currencies? As a string or something?
How to do this? We have to add two values 0.2 and 0.1, if we do it directly with JS we already know that there will be problems. 1) Multiply each value by 100: (0.2 * 100 + 0.1 * 100) = 30 cents. 2) Recover the value to money: (0.2 * 100 + 0.1 * 100) / 100 = 0.3.
currency. js is a lightweight ~1kb javascript library for working with currency values. It was built to work around floating point issues in javascript. This talk by Bartek Szopka explains in detail why javascript has floating point issues.
[...] and there is no real integer type. Is this accurate?
Yes.
If there is no integer type, then how can I accurately store currencies?
You can still use values that we would consider as integers, i.e. 5
, 42
, etc. Those values are accurate. "Integer" values only lose precision if they are > 2^53.
What you should avoid, in any language, is using rational numbers to represent currency, if you perform any computation with it. Meaning, instead of 4.13
, you should use 413
.
See Why not use Double or Float to represent currency?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With