代碼如下:

toFixed() 方法

var num =2.446242342;
num = num.toFixed(2);  // 輸出結果為 2.45

另外像 round()floor()ceil() 等都不能真正的四舍五入,有精度問題。

round() 可以通過以下方式來確保精度是正確的:

round() 方法

var num =2.446242342;
num = Math.round((num + Number.EPSILON) * 100) / 100;  // 輸出結果為 2.45