vue 使用decimal.js 解决小数相加合计精确度丢失问题

  • 安装依赖 decimal.js
    • npm install --save decimal.js
  • 封装
    • 在utils文件夹下创建decimal.js文件
js 复制代码
import { Decimal } from 'decimal.js'
export function add (x, y) {
    if (!x) {
        x = 0
    }
    if (!y) {
        y = 0
    }
    const xx = new Decimal(x)
    const yy = new Decimal(y)
    return xx.plus(yy).toNumber()
}
// 减
export function sub (x, y) {
    if (!x) {
        x = 0
    }
    if (!y) {
        y = 0
    }
    const xx = new Decimal(x)
    const yy = new Decimal(y)
    return xx.sub(yy).toNumber()
}
// 除
export function div (x, y) {
    if (!x) {
        x = 0
    }
    if (!y) {
        return 0
    }
    const xx = new Decimal(x)
    const yy = new Decimal(y)
    return xx.div(yy).toNumber()
}
//乘
export function mul (x, y) {
    if (!x) {
        x = 0
    }
    if (!y) {
        y = 0
    }
    const xx = new Decimal(x)
    const yy = new Decimal(y)
    return xx.mul(yy).toNumber()
}
  • 页面使用
vue 复制代码
<script>
  import {add} from "@/utils/decimal"
  export default {
    methods:{
      handlePlus() {
        add(10.5,4.877)
      }
    }
  }
</script>
相关推荐
喵本喵叁肆1 小时前
06-M6-部门过滤与综合研判-从问答机到研判助手
前端·javascript·jquery
卤蛋fg61 小时前
vue表格组件 vxe-table 鼠标滑动表头选择整列与选择整行的配置详解
vue.js
এ慕ོ冬℘゜1 小时前
JavaScript学习心得:从只会语法,到真正会写业务逻辑
开发语言·javascript·ecmascript
এ慕ོ冬℘゜2 小时前
jQuery 核心方法
前端·javascript·jquery
阳火锅2 小时前
老板要周报?我说不用,代码提交就是进度
前端·javascript·vue.js
chjif2 小时前
一张照片和一段声音如何生成口播视频:MiniMax H3 音画同步实测
java·前端·javascript
FungLeo2 小时前
成为全栈·Node 后端篇·后端工程从零搭建:TypeScript、目录与热更新
javascript·typescript·node 后端
Y3815326624 小时前
body-upload-js
前端·javascript·浏览器·深拷贝·数据克隆
Json____4 小时前
java-宿舍安全卫生检查系统项目源码
java·前端·javascript·课程设计·it学习·wwwoop.com