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>
相关推荐
an3174228 分钟前
解决 VSCode 中 ESLint 格式化不生效问题:新手也能看懂的配置指南
前端·javascript·vue.js
Lee川2 小时前
🚀《JavaScript 灵魂深处:从 V8 引擎的“双轨并行”看执行上下文的演进之路》
javascript·面试
比特鹰3 小时前
手把手带你用Flutter手搓人生K线
前端·javascript·flutter
大雨还洅下3 小时前
前端JS: 数组扁平化
javascript
奔跑路上的Me3 小时前
前端导出 Word/Excel/PDF 文件
前端·javascript
bluceli3 小时前
JavaScript异步编程深度解析:从回调到Async Await的演进之路
前端·javascript
青青家的小灰灰3 小时前
Vue 3 新标准:<script setup> 核心特性、宏命令与避坑指南
前端·vue.js·面试
SuperEugene3 小时前
路由与布局骨架篇:布局系统 | 头部、侧边栏、内容区、面包屑的拆分与复用
前端·javascript·vue.js
代码煮茶3 小时前
前端网络请求实战 | Axios 从入门到封装(拦截器 / 错误处理 / 重试)
javascript
进击的尘埃3 小时前
组合式函数 Composables 的设计模式:如何写出可复用的 Vue3 Hooks
javascript