輕量級的貨幣金額處理庫currency.js的使用

貨幣金額計算等。因爲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

千里之行
始於足下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章