我知道這之前已經被問過很多次了,我們已經解決了一個關于兩位小數的四舍五入金額(貨幣)的解決方案:
const myCurrencyAmount = Number(Math.round(totalAmount 'e' 2) 'e-' 2)
然而,現在非常非常接近 2022 年,埃隆·馬斯克即將送人到火星(嗯,首先是月球,但是......)所以肯定有更好的方法來(安全地!)在 Node.js 中繞行(安全!)。 js現在......?
上述解決方案已經運行了一段時間(幾年),但是一旦您想開始添加或使用兩位小數進行計算(例如在發票中),跟蹤所有數字的四舍五入很快就會變得困難,所有時間!
因為在 Node.js 中,當然,如果您將一個數字四舍五入一次,保留兩位小數,它不會記住這一點,并且下次您想重新讀取混淆計算的變數時,它不會再次使用它的浮點數...
而對于你,誰想但為什么不簡單地使用.toFixed(2),我可以告訴你,花車的世界遲早會給你帶來一些傷害......或者,同時享受這些可愛的樣本:
const num = 35.855;
console.log(num.toFixed(2));
// LOGS: 35.85
const num2 = 1.005;
console.log(num2.toFixed(2));
// LOGS: 1.00
然后想象一下用數千個數量總結幾千個發票行,看看這些舍入錯誤有多少讓你失望......
請注意,我不是在問浮點數(正如我所理解的那樣),我只是要求一個寫更少字符的解決方案......
uj5u.com熱心網友回復:
我建議為此目的查看一個專用庫,例如currency.js。這可以處理您關心的大多數問題,它專為此用例而設計。
例如:
console.log('7.66 0.01:',currency(7.66).add(.01).value);
console.log('$1.52 - $0.02:', currency('$1.52').subtract('$0.02').format());
let c1 = currency(2.03);
let c2 = currency(3.29);
console.log('11.66 2.03 3.29:', currency(11.66).add(c1).add(c2).value);
// With GBP
console.log('\nGBP example');
const invoiceAmount = currency(113535, { symbol: "£" });
const discountRate = 0.05;
const vatRate = 0.125;
const discount = invoiceAmount.multiply(discountRate);
const invoiceIncDiscount = invoiceAmount.subtract(discount);
const vat = invoiceIncDiscount .multiply(vatRate);
const invoiceTotal = invoiceIncDiscount .add(vat);
console.log('Invoice amount:'.padEnd(30), invoiceAmount.format().padStart(20));
console.log(`Discount (${discountRate*100}%):`.padEnd(30), discount.format().padStart(20));
console.log('Invoice (with discount):'.padEnd(30), invoiceIncDiscount .format().padStart(20));
console.log(`VAT (${vatRate*100}%):`.padEnd(30), vat.format().padStart(20));
console.log('Invoice (inc. VAT):'.padEnd(30), invoiceTotal.format().padStart(20));
// From the docs (European number format '€' symbol
console.log('\nEuro example');
const euro = value => currency(value, { symbol: "€", separator: ".", decimal: "," });
console.log('€2.573.693,75 €100.275,50 =', euro("2.573.693,75").add("100.275,50").format());
console.log('€1.237,72 - €300 =', euro("1.237,72").subtract(300).format());
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/currency.js/dist/currency.min.js"></script>
如果您正在尋找更通用的舍入函式,我會看看lodash round,這會將數字舍入到任意精度。
const num = 35.855;
console.log(_.round(num, 2));
const num2 = 1.005;
console.log(_.round(num2, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362840.html
上一篇:如何使用模10^9 7
