简体   繁体   中英

Getting a sum without rounding it off to two decimal places

Forgive me if I'm too noob about this. Recently, I post a question regarding the rounding off two decimal places. Now, How can I get the sum of these numbers but I only need the two decimals w/out rounding it off. This is javascript im working.

Example: 12.876 + 36.278 = 49.154. I need this answer to be... 49.15 only. Or another one: 12.876 + 1 = 13.876. I need this answer to be... 13.87

Here is my code (with round off to two decimal places)

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)*10)/10;
document.addition.civ123.value=valNum1;
}

Super thanks to those who are helping me everyday! :)

Math.floor(N * 100) / 100

Will strip off past two decimal places; Math.floor() is essentially Round Down no matter what.

Math.floor(N * 100) / 100 may not work always.

For Example,

4.56 becomes 4.55

If myNumber is the number you want to have two decimals...

myNumber.toFixed(2)

should work. Source: http://www.w3schools.com/jsref/jsref_tofixed.asp

A very old question, but I saw it didn't have an acceptable answer. As @user3006769 mentioned, some numbers don't work if you use Math.floor(N*100)/100.

Another approach is to count how many digits there are before the decimal, then convert your number to a string, chop off any characters to the right of the 2nd decimal, then convert it back to a number:

function roundDownDecimals(num, decimals) {
  const preDecimalDigits = Math.floor(num).toFixed(0).length;
  return parseFloat(num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1));
}

roundDownDecimals(4.56, 2);
// returns 4.56

roundDownDecimals(13.876, 2);
// returns 13.87

roundDownDecimals(4.10, 2);
// returns 4.1

If you need to preserve trailing 0's, leave off the parseFloat .

function roundDownDecimals(num, decimals) {
  const preDecimalDigits = Math.floor(num).toFixed(0).length;
  return num.toFixed(decimals + 1).slice(0, preDecimalDigits + decimals + 1);
}

roundDownDecimals(4.10, 2);
// returns "4.10"

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