将结果四舍五入到小数点后两位

时间:2011-03-24 06:27:20

标签: javascript decimal

我正在研究我的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(我忘了)。感谢那些愿意帮助的人。

3 个答案:

答案 0 :(得分:4)

操作顺序......

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

答案 1 :(得分:2)

试试这个:

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

答案 2 :(得分:1)

试试这个 valNum1 = Math.round((CIV1 + CIV2 +文明3 +文明4 + civ5 + civ6 + civ7)* 100)/ 100;
你错位了牙箍