[英]Rounding the result of division in Javascript
我在Javascript中執行以下操作:
0.0030 / 0.031
如何將結果舍入到任意數量的位置? var
將保持的最大數量是多少?
現代瀏覽器應該支持一個名為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的問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.