Freecodecamp: Some math operations give wrong results

Created on 2 Oct 2019  路  7Comments  路  Source: freeCodeCamp/freeCodeCamp

If you make some simple computations like addition or division the result is not correct

Steps to reproduce the behavior:

  1. Go to any lesson from java Javascript Algorithms And Data Structures Certification (300 hours)
  2. Write on the codding area console.log(96.74 - 60) or the division
  3. See the result
  4. See error

Expected behavior:
96.74 - 60 = 36.74

Actual result:
35.739999999999995

image

  • OS: Windows 10
  • Browser chrome, safari
bug

Most helpful comment

To expand slightly on what @raisedadead is saying, it's how floating point (decimal numbers) arithmetic is implemented. When evaluating things like 96.74 - 60, computers have to work using a binary representation which is generally going to create small rounding errors like the ones you've been seeing.

All 7 comments

From your screenshot it is returning 36.739999999999995 and not 35.739999999999995

See:

image

As for the precision that's how browser implement it. To round off, you need to to a toFixed

You can learn more about this on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

yes, you are right, I made a mistake there but still it is the wrong value, it should be 36.74. I will try to add to fixed and see if it helps

I am closing this, unless you have some additional information on how this can affect a lesson.

Also you can reach out to our Community Forum if you need help with a challenge.

using toFixed() does not help, I do not want to round the value, I just need the correct answer for the operation

I just need the correct answer for the operation

We understand your frustration. As I mentioned the precision after the decimals is what the browsers implement.

Since I do not have much information or context about what you are doing, it would help to share more information.

Did you try 36.739999999999995.toFixed(2) ? Did you go through the MDN docs?

using toFixed(2) helped for this case, thank you!

To expand slightly on what @raisedadead is saying, it's how floating point (decimal numbers) arithmetic is implemented. When evaluating things like 96.74 - 60, computers have to work using a binary representation which is generally going to create small rounding errors like the ones you've been seeing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danielonodje picture danielonodje  路  3Comments

DaphnisM picture DaphnisM  路  3Comments

Tzahile picture Tzahile  路  3Comments

MelissaManning picture MelissaManning  路  3Comments

vaibsharma picture vaibsharma  路  3Comments