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>
相关推荐
渣哥10 分钟前
代理选错,性能和功能全翻车!Spring AOP 的默认技术别再搞混
javascript·后端·面试
WeilinerL31 分钟前
泛前端代码覆盖率探索之路
前端·javascript·测试
咖啡の猫1 小时前
Vue 实例生命周期
前端·vue.js·okhttp
JNU freshman1 小时前
vue 之 import 的语法
前端·javascript·vue.js
剑亦未配妥1 小时前
Vue 2 响应式系统常见问题与解决方案(包含_demo以下划线开头命名的变量导致响应式丢失问题)
前端·javascript·vue.js
爱吃的强哥1 小时前
Vue2 封装二维码弹窗组件
javascript·vue.js
凉柚ˇ1 小时前
Vue图片压缩方案
前端·javascript·vue.js
ByteCraze1 小时前
秋招被问到的常见问题
开发语言·javascript·原型模式
优弧1 小时前
Vue 和 React 框架对比分析:优缺点与使用场景
vue.js
渣哥2 小时前
从代理到切面:Spring AOP 的本质与应用场景解析
javascript·后端·面试