前端数据精度问题解决方案

背景说明

前端精度问题是很普遍的问题,怎么解决呢?

解决方案

安装  npm install decimal.js

封装成工具

  // utils.decimal.js
import Decimal from 'decimal.js'
// 加
Decimal.add = function add(x, y) {
    return new this(x).plus(y).toString()
}
// 减
Decimal.sub = function sub(x, y) {
    return new this(x).sub(y).toString()
}
// 乘
Decimal.mul = function (x, y) {
    return new this(x).mul(y).toString()
}
// 除
Decimal.div = function div(x, y) {
    return new this(x).div(y).toString()
}
Decimal.toFixed = function div(x, y) {
    return new Decimal(x).toFixed(y).toString()
}

export default Decimal

使用方法

  import Decimal from './utils.decimal.js'
  const total = Decimal.add(num1, num2)

总结一下

这个插件很小 但可以解决前端精度问题,很不错,记录下来,供大家使用啦~~~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容