I ❤ #javascript: Is Math broken in JS?


You think you know the result of the sum of
this? Here comes, the answer equal to this is wrong! Are you kidding with me? Why so? Let’s clear it up. [Music playing] Hi let’s talk today about floating point Math
in JavaScript. I’m Anatol and you’re watching the Good Parts
of the FrontEnd development. [Music playing] It’s not just a JS problem, but a more general
computer one. See, the thing is, a computer lives in the
Binary World. Considering JavaScript, it uses 64-bit floating
point representation. What’s more, in most of the programming
languages numbers’ representation is based on international standard. According to this standard, the format is
following: a number times a power of two. So… Rational number whose denominator is not a
power of two (0.1, which is 1/10) cannot be represented precisely. For example, you can try yourself. It’s true. Сounter example. False, because it is equal to that. Number representation always depends on the
programming language. Some languages round the numbers with ‘Some
error constant’ also known as an Epsilon value. You can check this web page to see how exactly
they overcome this issue. The same issue you can see in C, and in Closure,
and even in Java. This issue in JavaScript can be solved through
various ways: You can use toFixed method
or you can use toPrecision method or you can use “multiply” and “divide” operations
or you can use a “Number.EPSILON” value or even you can use Math.js library That’s it. As you could see, it’s not a JavaScript problem. [Music playing] If you like this video give it “thumbs up”,
share it with your friends, subscribe to the channel and watch other episodes. Thanks for watching and dive deeper.

3 Comments

Add a Comment

Your email address will not be published. Required fields are marked *