# Why it works this way?

Watched video about js. There was a code

``````const num = 0.1 + 0.2
console.log(num === 0.3) //false

//but if num = 0.1 + 0.3
console.log(num === 0.4) //true
``````

How it works?

Because of the way that floating point numbers are stored, some decimal numbers cannot be stored exactly. How do you store a decimal fraction in a binary fraction perfectly?

If you need that kind of precision with floating point numbers, you can either be sure to round things off intelligently or you can check if the answer is within the āpossible error of JS floating point arithmetic on whatever system you are usingā. How do you know what that is? It is given to you in the value Number.EPSILON.

``````const num = 0.1 + 0.2
console.log(num === 0.3) //false

const difference = Math.abs(num - 0.3)
console.log(difference <= Number.EPSILON) //true
``````
2 Likes

Yes, this is weird. Yes, it isnāt intuitive (if you havenāt done a lot of binary math.) Donāt worry about it - itās usually not an issue. In the rare cases where it is, you can deal with it. There are also libraries that are specifically built for high precision math that deal with these kinds of things nicely.

Cool! But how can I answer this question when 0.1 + 0.2 !== 0.3 , but 0.1 + 0.3 === 0.4? What if here will be another values with *.n

I think @kevinSmith explained the concept nicely. But if you are looking for an answer about how to do this in code, other than using a specialty math library (as Kevin suggested), you could multiply all of the numbers involved by a power of 10 to remove the decimal and then compare them. So in this case if you multiplied them all by 10 (since you only have one number after the decimal) then you would have 1 + 2 === 3 which would be true.

Iām talking about job test. There was a question

console log (0,1+0,2 === 0,3) // true or false

I guess I donāt understand your question. What exactly are you asking for help with here?

I think heās asking about getting this question on a test to get a job.

First thing I notice is that it is using commas instead of decimal points. Some countries use commas as decimal separators, but In the JS we use decimal points - that code is not valid JS. It is also missing a period in the console.log.

So the code you give will give a syntax error.

If you meant:

``````console.log(0.1+0.2 === 0.3) // true or false
``````

I think it is a simple matter to type it into the console to find that the answer is false. And weāve already explained why.

thanks!

ŠæŠ½, 21 ŃŠµŠ½Ń. 2020 Š³., 3:00 Kevin Smith via The freeCodeCamp Forum <freecodecamp@discoursemail.com>: