货币金额计算等。因为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
千里之行
始于足下