我在 Javascript 中执行以下操作:
0.0030 / 0.031
如何将结果四舍五入到任意数量的位置?var
a将持有的最大数量是多少?
现代浏览器应该支持一种名为toFixed()
. 下面是一个取自网络的例子:
// 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()
将四舍五入到最接近的整数。为了达到小数精度,您需要稍微操作一下您的数字:
因此,要将 5.11111111 舍入到小数点后三位,您可以这样做:
var result=Math.round(5.111111*1000)/1000 //returns 5.111
数字类型的最大正有限值约为1.7976931348623157 * 10 308。ECMAScript-262 第 3 版。还定义了Number.MAX_VALUE
哪个持有该值。
回答 Jag 的问题: