-5

I am new to coding/JavaScript and I'm trying to understand why one of my loops refuses to run as I intended.

Basically, I am setting a loop that only outputs a certain part (fraction) of 100. As you can see in the snapshot, everything works fine when I am outputting quarters. However, when I attempt to output tenths, the loop stops after two-tenths, when it should output ten-tenths.

Both loops are exactly the same, syntax wise. Would anyone mind explaining why one runs, while the other doesn't? Thanks in advance!

var quarter = .25;
for (x = 1; x <=100; x++)
{
    if (x / 100 === quarter)
    {
       console.log (x + " is one of the quarter");
       quarter = quarter + .25;
    }
}

console.log (" ");

var part = .1;
for (x = 1; x <=100; x++)
{
    if (x / 100 === part)
    {
       console.log (x + " is one of the part");
       part = part + .1;
}

}

Snapshot of Editor + Terminal with Code in Question

  • 1
    Please copy & paste your code sample into your question instead of linking to a screenshot. – Adrian May 18 '17 at 18:31

2 Answers2

0

Try this code out:

code

var part=0.1;
for(x=1;x<=100;x++){
if(x/100===part){
   console.log(x);
   part=parseFloat((part+.1).toFixed(1));
}
}

The problem is 0.1+0.1+0.1= 0.300000004 in javascript which can be fixed using the above code

0

The reason is JS not good at floating point addition, and it will not output what you noramlly will expect

> console.log(0.2+.1)
> 0.30000000000000004

Copied from another stackoverflow(Weird Javascript Behaviour: Floating Point Addition giving the wrong answer)

It has to do with how decimal values are converted to binary floating point numbers. 1/10 turns into a repeating decimal in binary, so the number is not perfectly represented, and repeated operations can expose the error.

JavaScript uses IEEE-754 floating point numbers, for the record. Some other languages have the same problem.

checkout this also: Is floating point math broken?

Community
  • 1
  • 1
Kumar Nitesh
  • 1,634
  • 15
  • 18