Question

I've searched through google (maybe I didn't look hard enough) but I could not find how to turn Math.sqrt into an int.

I want to use Math.sqrt for a for loop and I guess I need it as an int but I can't seem to figure out how to cast the result to an int. So how do I do it?

I tried something similar to Java:

(int) Math.sqrt(num);

But it didn't work.

Thanks in advance :)

Was it helpful?

Solution

Use Math.round, Math.ceil, or Math.floor depending on your specific rounding needs.

"For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable, and for a desired result that can be expressed as a 32 bit signed integer the bitwise operation described below might also suit."

-http://www.jibbering.com/faq/faq_notes/type_convert.html#tcNumber

OTHER TIPS

Someone suggested parseInt. That goes from a string to an int, but it's easy to turn a float into a string.

parseInt(Math.sqrt(num)+"")

Remember that no matter what you do, JavaScript is always using floats. There is no integer type.

Math.floor will do it. Doubt you even need to go to an integer, though.

Math.floor(Math.sqrt(num));

Using parseInt(Math.sqrt(num)+"") is slower than using Math.round(Math.sqrt(num)). I think it is because in first example you are creating string, parsing integer value of num and rounding it. in second example you just take int and round it.

i know this is an old question, but i figure for anyone finding this later....

i won't reiterate what the other answers say, but a fun little trick you can do is:

Math.sqrt(2); //1.41......
~~Math.sqrt(2); //1

the double bitwise negative drops off anything after the decimal point. i've been told it's slightly faster, but i'm not entirely convinced.

EDIT: as a note this will round toward 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top