简体   繁体   中英

Round off the results to two decimal places

I'm working on my javascript. I want it to sum in two decimal places. So if I add: 25.321+300.693 = 326.014

I want the sum to be: 326.01. Here's my code:

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

I also try this one:

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

But the result is incorrect. I add 2 numbers again (128.65 + 0 ) = 1.29 or 1.28 (I forgot). Thanks for those who will help.

操作顺序...

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

Try this:

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

try this valNum1=Math.round((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*100)/100;
you misplace the braces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM