在Javascript中舍入除法的结果

编程入门 行业动态 更新时间:2024-10-23 16:26:58
本文介绍了在Javascript中舍入除法的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在Javascript中执行以下操作:

I'm performing the following operation in Javascript:

0.0030 / 0.031

0.0030 / 0.031

如何将结果舍入到任意数量的位置? var 的最大数量是多少?

How can I round the result to an arbitrary number of places? What's the maximum number that a var will hold?

推荐答案

现代浏览器应该支持一个名为 toFixed()的方法。以下是网上举例:

Modern browsers should support a method called toFixed(). Here's an example taken from the web:

// Example: toFixed(2) when the number has no decimal places // It will add trailing zeros var num = 10; var result = num.toFixed(2); // result will equal 10.00 // Example: toFixed(3) when the number has decimal places // It will round to the thousandths place num = 930.9805; result = num.toFixed(3); // result will equal 930.981

toPrecision()也可能对你有用,在那个页面上有另一个很好的例子。

toPrecision() might also be useful for you, there is another excellent example on that page.

对于旧版浏览器,你可以实现它手动使用 Math.round 。 Math.round()将舍入到最接近的整数。为了达到小数精度,你需要稍微操纵你的数字:

For older browsers, you can achieve it manually using Math.round. Math.round() will round to the nearest integer. In order to achieve decimal precision, you need to manipulate your numbers a bit:

  • 将原始数字乘以10 ^ x (10为x的幂),其中x为 想要的小数位数。
    • 申请Math.round()
    • 除以10 ^ x
    • 所以要将5.11111111舍入到三位小数,你可以这样做:

      So to round 5.11111111 to three decimal places, you would do this:

      var result=Math.round(5.111111*1000)/1000 //returns 5.111
  • 更多推荐

    在Javascript中舍入除法的结果

    本文发布于:2023-10-25 13:42:28,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1527116.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:除法   Javascript   中舍入

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!