如何在javascript中进行整数除法(在int中得到除法答案不浮动)?

Nak*_*kib 88 javascript division integer-division

Javascript中是否有任何函数可以让你进行整数除法,我的意思是在int中得到除法答案,而不是浮点数.

var x = 455/10;
// Now x is 45.5
// Expected x to be 45
Run Code Online (Sandbox Code Playgroud)

但我希望x为45.我试图消除数字中的最后一位数字.

Nee*_*raj 210

var answer = Math.floor(x)
Run Code Online (Sandbox Code Playgroud)

我真诚地希望这会在搜索这个常见问题时帮助未来的搜索者.

  • 我发现具有讽刺意味的是,这是我谷歌搜索中如何解决这个问题的最佳答案. (41认同)
  • 我发现这个答案一直都不正确.如果结果为负数,则"Math.floor()"返回错误的结果.因此,即使谷歌也会回复一个不那么正确的答案.这里:http://stackoverflow.com/questions/4228356/integer-division-in-javascript (17认同)
  • Math.trunc() 解决负值问题。事实上,如果您只想删除小数部分,那么 trunc 就是您所需要的。/sf/answers/1561500531/ (9认同)
  • 这里使用`Math.floor()`仅适用于给定数字为正的情况.[看看这个以获得更多解释](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Math/floor).通常``parseInt()`是一个更好的选择来获取数字或字符串的整数部分. (8认同)
  • 谢谢我谷歌搜索但无法找到,谢谢:) (4认同)
  • @ShaunKruger具有讽刺意味的是,它的答案是q吗?也许不是很好。听起来像parseInt更好。 (2认同)

ST3*_*ST3 25

var x = parseInt(455/10);
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

  • 这是低效的,因为它有一个隐式的`number.toString()`调用,而不是``parse`,与`Math.floor`相比相对昂贵.不能保证`parseInt`会接受`number`参数. (23认同)