如何从JavaScript编号中删除小数部分? [英] How can I remove the decimal part from JavaScript number?

查看:152
本文介绍了如何从JavaScript编号中删除小数部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有分组的结果,我希望丢弃结果数字的小数部分。

I have the results of a division and I wish to discard the decimal portion of the resultant number.

我该怎么做?

推荐答案

你可以使用......

You could use...

  • Math.trunc() (truncate fractional part, also see below)
  • Math.floor() (round down)
  • Math.ceil() (round up)
  • Math.round() (round to nearest integer)

...取决于你想要删除的方式十进制。

...dependent on how you wanted to remove the decimal.

所有平台(即IE)都不支持Math.trunc(),但是您可以轻松使用 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编号中删除小数部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆