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>
相关推荐
比老马还六14 分钟前
element-ui,使用el-table时,type=“expand“和fixed一起使用坑
开发语言·javascript·ui
晴天丨15 分钟前
🔔 如何实现一个优雅的通知中心?(Vue 3 + 消息队列实战)
前端·vue.js
天天向上102415 分钟前
vue openlayers地图加载大量线条时优化
javascript·vue.js·ecmascript
竹林81821 分钟前
Next.js 14 + wagmi v2 构建 NFT 市场:从列表渲染到链上交易的全链路实践
javascript·next.js
幸运小圣22 分钟前
Array.prototype.reduce 全面解析【JS方法】
开发语言·javascript·原型模式
Ruihong22 分钟前
你的 Vue TransitionGroup 组件,VuReact 会编译成什么样的 React 代码?
vue.js·react.js·面试
星晨雪海28 分钟前
若依框架原有页面功能进行了点位管理模块完整改造(3)
开发语言·前端·javascript
sensen_kiss30 分钟前
CAN302 Coursework1对 JavaScript 和 PHP 的考察
javascript·学习·php
morethanilove42 分钟前
新建vue3 + ts +vite 项目
前端·javascript·vue.js