问题描述
我有除法的结果,我希望舍弃结果数的小数部分.
I have the results of a division and I wish to discard the decimal portion of the resultant number.
我该怎么做?
推荐答案
你可以使用...
Math.trunc()代码>(截断小数部分,另见下文)
Math.floor()
(向下取整)Math.ceil()
(四舍五入)Math.round()
(四舍五入到最接近的整数)
...取决于您要如何删除小数.
...dependent on how you wanted to remove the decimal.
Math.trunc()
尚不支持所有平台(即 IE),但您可以轻松使用 polyfill 同时.
Math.trunc()
isn't supported on all platforms yet (namely IE), but you could easily use a polyfill in the meantime.
另一种截断小数部分并具有出色平台支持的方法是使用 位运算符 (.eg |0
).对数字使用按位运算符的副作用是将其操作数视为带符号的 32 位整数,因此会删除小数部分.请记住,这也会破坏大于 32 位的数字.
Another method of truncating the fractional portion with excellent platform support is by using a bitwise operator (.e.g |0
). The side-effect of using a bitwise operator on a number is it will treat its operand as a signed 32bit integer, therefore removing the fractional component. Keep in mind this will also mangle numbers larger than 32 bits.
您可能还在谈论浮点运算的十进制舍入的不准确性.
You may also be talking about the inaccuracy of decimal rounding with floating point arithmetic.
必读 - 每个计算机科学家都应该知道的浮点运算.
这篇关于如何从 JavaScript 数字中删除小数部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!