在Javascript中舍入除法的结果

时间:2009-09-02 22:37:47

标签: javascript rounding

我在Javascript中执行以下操作:

  

0.0030 / 0.031

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

3 个答案:

答案 0 :(得分:13)

现代浏览器应支持名为toFixed()的方法。这是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()也可能对您有用,该页面上还有另一个很好的例子。


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

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

    var result=Math.round(5.111111*1000)/1000  //returns 5.111
    

答案 1 :(得分:2)

数字类型的最大正有限值约为 1.7976931348623157 * 10 308 。 ECMAScript-262第3版。还定义了保存该值的Number.MAX_VALUE

答案 2 :(得分:1)

回答Jag的问题:

  1. 使用toFixed()方法。谨防;它返回一个字符串,而不是一个数字。
  2. 十五岁,也许就十六岁。如果你试图获得更多,额外的数字将是零或垃圾。尝试格式化1/3之类的东西来看看我的意思。
相关问题