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>
相关推荐
爱吃甜品的糯米团子7 分钟前
详解 JavaScript 内置对象与包装类型:方法、案例与实战
java·开发语言·javascript
华仔啊9 分钟前
JavaScript + Web Audio API 打造炫酷音乐可视化效果,让你的网页跟随音乐跳起来
前端·javascript
程序定小飞42 分钟前
基于springboot的学院班级回忆录的设计与实现
java·vue.js·spring boot·后端·spring
是你的小橘呀1 小时前
深入理解 JavaScript 预编译:从原理到实践
前端·javascript
攀小黑1 小时前
基于若依-内容管理动态修改,通过路由字典配置动态管理
java·vue.js·spring boot·前端框架·ruoyi
风止何安啊1 小时前
栈与堆的精妙舞剧:JavaScript 数据类型深度解析
前端·javascript
用户47949283569151 小时前
Chrome DevTools MCP:让 AI 助手直接操作浏览器开发工具
前端·javascript·chrome
Rysxt_1 小时前
Vuex 教程 从入门到实践
前端·javascript·vue.js
xuehuayu.cn2 小时前
js es6 class 类中的值是异步赋值, 子类中如何获取这个值?
javascript·es6
威风的虫2 小时前
ES6 数组方法:告别循环,拥抱函数式编程
开发语言·前端·javascript