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>
相关推荐
daols8818 小时前
vue2 表格如何使用 vxe-table 带列头复制单元格内容同步到 excel 中
vue.js·excel·vxe-table
晚霞的不甘19 小时前
Flutter for OpenHarmony 布局核心:Row 与 Column 深度解析与实战
android·前端·javascript·flutter
ethan.Yin19 小时前
element-plus 二次封装遇到的一点疑惑
javascript·vue.js·ecmascript
Ulyanov19 小时前
Impress.js 3D立方体旋转个人年终总结设计与实现
开发语言·前端·javascript·3d·gui开发
榴莲不好吃19 小时前
前端js图片压缩
开发语言·前端·javascript
切糕师学AI19 小时前
Vue 中的 keep-alive 组件
前端·javascript·vue.js
可问春风_ren19 小时前
Git命令大全
前端·javascript·git·后端
她说彩礼65万19 小时前
Jquery总结
前端·javascript·jquery
光影少年19 小时前
前端如何定位组件变化及性能问题
前端·javascript·react.js
芳草萋萋鹦鹉洲哦20 小时前
【Vue 3/Vite】Tailwind CSS稳定版安装替代CDN引入
前端·css·vue.js