在Javascript中舍入除法的结果 [英] Rounding the result of division in 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中舍入除法的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!