0

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/

GROVER.
  • 3,082
  • 1
  • 11
  • 48

1 Answers1

1

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.

ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61
  • I'll give it a shot! Thanks for the answer – GROVER. Feb 07 '17 at 11:06
  • Hi, I'm trying it now, it's semi-fixed my problem in that in now stops at `3.17`, instead of `1.42` – GROVER. Feb 07 '17 at 11:40
  • @GROVER. at any given input! – ibrahim mahrir Feb 07 '17 at 11:42
  • @GROVER. if you're really stubborn about reinventing the square root function, then check this two link: [**same question on stackoverflow**](http://stackoverflow.com/questions/1623375/writing-your-own-square-root-function) and [**wikepedia page on the same topic**](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots). I hope your hair won't grey! – ibrahim mahrir Feb 07 '17 at 12:01