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

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.


пн, 21 сент. 2020 г., 3:00 Kevin Smith via The freeCodeCamp Forum <freecodecamp@discoursemail.com>: