GROVER.
GROVER.

Reputation: 4378

for loop increment with decimal stopping at 1.42 instead of continuing until calculation is complete

I have developed a simple little square root calculator within JavaScript, using a for loop.

However, I noticed when outputting each value for i every time the loop iterates (using console.log(i).toFixed(2)), the counting would stop at 1.42 every time.

Here is the JavaScript:

// inp is the input in which the user types the number they would like to find the square root of
for(var i = 0; i < inp.value; i += 0.01){
    var check = i * i;
    check = check.toFixed(2); // fix decimal to a tenth

    console.log(i.toFixed(2)); // output value to console

    if(check == inp.value){ // if i * i is equal to user input
        alert(i); // alert the square root
        break; // break out of for loop
    } else if(check > inp.value){ // if the value is more than user input
        alert("Value could not be found."); // alert value could not be found 
        break; // break out of for loop
    }
}

All help is appreciated,
Thanks.

EDIT: I have noticed that if I am to type in 1, it will output up until 0.99, as opposed to 1.42

EDIT No 2: I tested out Ibrahims new answer, and it semi-sort of worked. It now stops at 3.17, instead of 1.42. However, I noticed that after testing it out, my laptops fans would start spinning at full throttle, and my CPU load would spike to 100% for a brief second, before slowing to about 40%. Would it perhaps be the fact the laptop cannot handle the consistent for loop? If so, what would be a better alternative to this? Thanks

Fiddle: https://jsfiddle.net/pk7or60f/

Upvotes: 0

Views: 76

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

I had doubts about it but it was the error all along. .toFixed is returning a string (that's I know), inp.value is a string (that's I know too). But I thought that since > work with just numbers, that the interpretter will use their values as numbers and do the right comparison. But I was wrong about that. So to force the interpretter to see them as number, use the explicit way using Number or parseFloat like this:

else if(Number(check) > Number(inp.value)){
    alert("Value could not be found.");
    break;
}

or the implicit way using the unary + like this:

else if(+check > +inp.value){
    alert("Value could not be found.");
    break;
}

The same goes for equality check.

Upvotes: 1

Related Questions