簡體   English   中英

求和而不將其四舍五入到小數點后兩位

[英]Getting a sum without rounding it off to two decimal places

如果我對此太菜鳥,請原諒我。 最近,我發布了一個關於四舍五入小數點后的問題。 現在,我怎樣才能得到這些數字的總和,但我只需要兩位小數,而不是四舍五入。 這是我正在工作的 javascript。

示例:12.876 + 36.278 = 49.154。 我需要這個答案是... 49.15 only。 或者另一個:12.876 + 1 = 13.876。 我需要這個答案是... 13.87

這是我的代碼(四舍五入到小數點后兩位)

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

非常感謝每天幫助我的人! :)

Math.floor(N * 100) / 100

將去掉小數點后兩位; Math.floor()本質上都是向下Math.floor()

Math.floor(N * 100) / 100 可能並不總是有效。

例如,

4.56 變成 4.55

如果 myNumber 是您想要保留兩位小數的數字...

myNumber.toFixed(2)

應該管用。 來源: http : //www.w3schools.com/jsref/jsref_tofixed.asp

一個非常古老的問題,但我看到它沒有一個可以接受的答案。 正如@user3006769 所提到的,如果您使用 Math.floor(N*100)/100,某些數字將不起作用。

另一種方法是計算小數點之前有多少位數字,然后將您的數字轉換為字符串,切掉第二個小數點右側的所有字符,然后將其轉換回數字:

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

如果您需要保留尾隨的 0,請不要使用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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM