2011-03-24 116 views
1

我正在處理javascript。我希望它總計在兩位小數。所以如果我加: 25.321 + 300.693 = 326.014將結果舍入到小數點後兩位

我想要的總和爲:326.01。這裏是我的代碼:

function civ(){ 
civ1=Number(document.addition.scc.value); 
civ2=Number(document.addition.ccc.value); 
civ3=Number(document.addition.ncc.value); 
civ4=Number(document.addition.vch.value); 
civ5=Number(document.addition.mch.value); 
civ6=Number(document.addition.nlch.value); 
civ7=Number(document.addition.slch.value); 
valNum1=civ1+civ2+civ3+civ4+civ5+civ6+civ7; 
document.addition.civ123.value=valNum1; 
} 

我也試試這個:

function civ(){ 
civ1=Number(document.addition.scc.value); 
civ2=Number(document.addition.ccc.value); 
civ3=Number(document.addition.ncc.value); 
civ4=Number(document.addition.vch.value); 
civ5=Number(document.addition.mch.value); 
civ6=Number(document.addition.nlch.value); 
civ7=Number(document.addition.slch.value); 
valNum1=Math.round(civ1+civ2+civ3+civ4+civ5+civ6+civ7*100)/100; 
document.addition.civ123.value=valNum1; 
} 

但結果不正確。我再次添加2個數字(128.65 + 0)= 1.29或1.28(我忘了)。感謝那些願意幫助的人。

操作

回答

4

順序...

Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*100)/100; 
1

嘗試這種 valNum1 = Math.round((CIV1 + CIV2 +文明3 +文明4 + civ5 + civ6 + civ7)* 100)/ 100;
你放錯地方的括號

+0

嘿Ujjwal,謝謝! :) – catsgirl008 2011-03-24 06:42:51

2

試試這個:

var num = 15.65686354785 
var newnum = (num.toString().length > 4 ? num.toFixed(2) : num); 
相關問題