如何在 javascript 中进行整数除法(在 int 中得到除法答案而不是浮点数)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18928117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do integer division in javascript (Getting division answer in int not float)?
提问by Nakib
Is there any function in Javascript that lets you do integer division, I mean getting division answer in int, not in floating point number.
Javascript 中是否有任何函数可以让您进行整数除法,我的意思是在 int 中获得除法答案,而不是浮点数。
var x = 455/10;
// Now x is 45.5
// Expected x to be 45
But I want x to be 45. I am trying to eliminate last digit from the number.
但我希望 x 为 45。我试图从数字中消除最后一位数字。
回答by Neeraj
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
我真诚地希望这会在谷歌搜索这个常见问题时帮助未来的搜索者。
回答by ST3
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
parseInt() 函数解析一个字符串并返回一个整数。
radix 参数用于指定使用哪种数字系统,例如基数为 16(十六进制)表示字符串中的数字应从十六进制数解析为十进制数。
如果省略 radix 参数,JavaScript 假定如下:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)