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 小时前
自动化脚本中使用RSA
前端·javascript·自动化
只睡四小时2 小时前
AI 写的倒计时:Electron 每轮吞 0.8 秒
javascript·人工智能·性能优化·electron·时间管理·番茄钟
全速向光3 小时前
用 Three.js 从零打造一棵会发光的 3D 圣诞树
开发语言·javascript·3d
布语world3 小时前
某东pc滑块分析
前端·javascript·网络·python·安全
map_vis_3d4 小时前
百度地图自定义覆盖物 CustomOverlay:用 HTML、React、Vue 组件做标注
前端·javascript·vue·react·百度地图
变与不变8064 小时前
js数据流
前端·javascript
map_3d_vis5 小时前
百度地图折线 Polyline:颜色、虚线、方向箭头和纹理(JSAPI 4.0)
前端·javascript·地图·百度地图
智购科技自动贩卖机5 小时前
自动售货机SaaS多租户数据库实战:分库分表与租户隔离~YH
android·java·linux·开发语言·javascript·网络
RuoyiOffice6 小时前
Vue3商城后台实战:一款商品,从规格上架走到部分退款
vue.js·spring boot·vue3·商城系统·商城·企业管理·ruoyi office
htzyl20620 小时前
Vue3中watch的deep默认值:reactive与ref为什么相反
前端·vue.js