How can I remove the decimal part from JavaScript number?(如何从 JavaScript 数字中删除小数部分?)
问题描述
我有除法的结果,我希望舍弃结果数的小数部分.
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 数字中删除小数部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 JavaScript 数字中删除小数部分?
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
