貨幣金額計算等。因爲IEEE754 數值的浮點計算,js沒有處理浮點計算精度誤差問題,其他語言入java,c內部處理了。
currency.js傳送門
只有1kb的超級輕量級的處理貨幣金額的js庫
安裝currency.js
npm install --save currency.js
使用currency
node_modules
中已安裝名爲currency.js
打開currency.js
使用module.exports
導出模塊
那麼使用require
(‘模塊名’)引入。我們都知道對於node_moduels
直接require
模塊名而不是相對或絕對路徑。那麼這裏的模塊名爲currency.js
,千萬別寫成currency
引用並使用
var currency = require('currency.js')
function getCurrency(value, precision = 2) {
let cu=currency(value, { precision: precision }).add(0.2).format()
console.log(cu)
}
getCurrency(0.1)
getCurrency(30000)
可以看到金額精度確實木有問題了以及千分位也ok
千里之行
始於足下