2011-06-29 51 views
11

tôi có:cắt đến 2 số thập phân

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;" 

Hầu hết số vòng ok đến 2 điểm thập phân đó là những gì tôi cần.

Tuy nhiên, với một ví dụ như

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;" 

Dòng 1 đang trở lại 75.99000000000001 Làm thế nào tôi có thể cắt để 75.99 nhất quán không?

Trả lời

5

Sử dụng phương pháp toFixed(2) để sửa chữa nó ở mức 2 chữ số thập phân:

(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

Làm thế nào về điều này:

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

Phương pháp toFixed nên chăm sóc của làm tròn độc đáo cho bạn.

31
var num = 5/6; 

var display = num.toFixed(2) 

num outputs: 0.8333333333333334 

display outputs: "0.83" 
Các vấn đề liên quan