Javascript:将 Math.sqrt 转换为 int?
我已经通过谷歌进行了搜索(也许我看起来不够努力),但我找不到如何将 Math.sqrt 转换为 int 。
我想将 Math.sqrt 用于 for 循环,我想我需要它作为 int,但我似乎不知道如何将结果转换为 int。 那么我该怎么做呢?
我尝试了类似Java的方法:
(int) Math.sqrt(num);
但没有成功。
提前致谢 :)
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 :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根据您的具体舍入需求,使用
Math.round
、Math.ceil
或Math.floor
。“对于将数字舍入为整数,Math.round、Math.ceil 和 Math.floor 之一是首选,并且对于可以表示为 32 位有符号整数的所需结果,下面描述的按位运算也可能适合。”
-http://www.jibbering.com/faq/faq_notes/ type_convert.html#tcNumber
Use
Math.round
,Math.ceil
, orMath.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
有人建议parseInt。 从字符串到整数,但将浮点数转换为字符串很容易。
请记住,无论您做什么,JavaScript 始终使用浮点数。 没有整数类型。
Someone suggested parseInt. That goes from a string to an int, but it's easy to turn a float into a string.
Remember that no matter what you do, JavaScript is always using floats. There is no integer type.
Math.floor 就可以了。 不过,怀疑您甚至需要使用整数。
Math.floor will do it. Doubt you even need to go to an integer, though.
使用
parseInt(Math.sqrt(num)+"")
比使用Math.round(Math.sqrt(num))
慢。 我认为这是因为在第一个示例中您正在创建字符串,解析num
的整数值并将其四舍五入。 在第二个示例中,您只需采用 int 并将其舍入。Using
parseInt(Math.sqrt(num)+"")
is slower than usingMath.round(Math.sqrt(num))
. I think it is because in first example you are creating string, parsing integer value ofnum
and rounding it. in second example you just take int and round it.我知道这是一个老问题,但我想以后任何人都会发现这个问题......
我不会重申其他答案所说的内容,但你可以做的一个有趣的小技巧是:
双按位负数会在小数点。 有人告诉我它会稍微快一点,但我并不完全相信。
编辑:作为注释,这将四舍五入到 0。
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:
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.