Different languages have different idiosyncrasies when handling numbers.
Here are a few critical pieces of information about numbers in JavaScript that you should be aware of.
Number: the only number type in JavaScript is a double-precision 64-bit.
binary floating point numbers do not map correctly to Decimal numbers. This is how a famous calculation problem was produced in JavaScript.
console.log(.1 + .2); // 0.30000000000000004
For true decimal math use
big.js
mentioned below.
integer is limited by:
Number.MAX_SAFE_INTEGER
Number.MIN_SAFE_INTEGER
console.log({max: Number.MAX_SAFE_INTEGER, min: Number.MIN_SAFE_INTEGER});
// {max: 9007199254740991, min: -9007199254740991}
Safe in this context refers to the fact that the value cannot be the result of a rounding error.
The unsafe values are +1 / -1
away from these safe values and any amount of addition / subtraction will round the result.
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2); // true!
console.log(Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2); // true!
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MAX_SAFE_INTEGER + 1); // 9007199254740992 - Correct
console.log(Number.MAX_SAFE_INTEGER + 2); // 9007199254740992 - Rounded!
console.log(Number.MAX_SAFE_INTEGER + 3); // 9007199254740994 - Rounded - correct by luck
console.log(Number.MAX_SAFE_INTEGER + 4); // 9007199254740996 - Rounded!