2011-06-29 70 views
11

我:修剪到2位小數

onclick="document.getElementById('field1').value = 
Math.round((parseFloat(document.getElementById('field2').value,2)*100))/100 + 
Math.round((parseFloat(document.getElementById('field3').value,2)*100))/100;" 

大多數數字一輪確定以2個小數點這正是我需要的。

然而,像

onclick="document.getElementById('field1').value = 
Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 + 
Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100;" 

場爲例1返回75.99000000000001我怎麼能修剪75.99一致?

回答

5

使用方法toFixed(2)在小數點後2位,以解決它:

(Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 + 
    Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100).toFixed(2); 
2

如何:

parseFloat(document.getElementById('21.29').toFixed(2);

的toFixed方法應該很好地爲你四捨五入的照顧。

31
var num = 5/6; 

var display = num.toFixed(2) 

num outputs: 0.8333333333333334 

display outputs: "0.83"