Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Cast Math.sqrt to int?

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

like image 990
Nope Avatar asked Feb 01 '09 05:02

Nope


People also ask

Does Math sqrt return an int?

Return Values of Math. sqrt() method returns NaN i.e. Not a Number.

What type of value is returned by Math sqrt ()?

Math. sqrt() returns the square root of a value of type double passed to it as argument.

How do you round a number in JavaScript?

The Math.round() function returns the value of a number rounded to the nearest integer.


1 Answers

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

like image 70
Chris Ballance Avatar answered Sep 28 '22 09:09

Chris Ballance