Exploring numbers
JavaScript has good support for mathematical operations and dates, but sometimes it can be tricker and more limited than other programming languages, so many developers use specialized libraries when the application requires advanced math. For example, if you need to work with vectors, matrices, or complex numbers, you should use a library such as Math.js (https://mathjs.org/).
Here is a typical example of the floating-point precision problem:
console.log(0.1 + 0.2); // 0.30000000000000004 console.log(0.1 + 0.2 === 0.3); // false
As you can see, the result of 0.1 + 0.2
is not 0.3
, but 0.30000000000000004
. This is because JavaScript uses the IEEE 754 standard (https://en.wikipedia.org/wiki/IEEE_754) to represent numbers, and it is not possible to represent all decimal numbers in binary. This is a common problem in many programming languages; it is not an exclusively JavaScript problem. But you can solve it by using the Number
and toPrecision
functions as you...