[ACCEPTED]-Javascript: Cast Math.sqrt to int?-casting

Accepted answer
Score: 25

Use Math.round, Math.ceil, or Math.floor depending on your specific rounding 1 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

Score: 5

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

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

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

Score: 4

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

Math.floor(Math.sqrt(num));
Score: 3

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

Score: 1

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

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

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

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

EDIT: as 1 a note this will round toward 0.

More Related questions