views:

4106

answers:

3

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 :)

+7  A: 

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

Chris Ballance
+3  A: 

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

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

Nosredna
+2  A: 

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.

Nosredna
Edit your older question without re-posting.
Luca Matteis
Sorry. At the time I didn't seem to have the reputation to comment on the other guy's answer, which is what I was trying to do.
Nosredna
I think the negative vote is unwarranted considering that Nosredna didn't have the necessary rep to comment. Neutralized.
Cerebrus
Actually the javascript number type is a double, not a float.
Georg
gs, yeah thanks. The floating point spec used by ECMASCript is IEEE-754 double-precision floating-point. I did a blog post on it once, you'd think I'd remember. http://dreaminginjavascript.wordpress.com/2008/07/15/9007199254740992/
Nosredna