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>
相关推荐
Zheng1131 小时前
【可视化大屏】将柱状图引入到html页面中
javascript·ajax·html
john_hjy1 小时前
【无标题】
javascript
软件开发技术深度爱好者2 小时前
用HTML5+CSS+JavaScript庆祝国庆
javascript·css·html5
汪子熙2 小时前
Angular 服务器端应用 ng-state tag 的作用介绍
前端·javascript·angular.js
杨荧2 小时前
【JAVA开源】基于Vue和SpringBoot的旅游管理系统
java·vue.js·spring boot·spring cloud·开源·旅游
一 乐7 小时前
学籍管理平台|在线学籍管理平台系统|基于Springboot+VUE的在线学籍管理平台系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习
昨天;明天。今天。8 小时前
案例-表白墙简单实现
前端·javascript·css
安冬的码畜日常8 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine
小御姐@stella8 小时前
Vue 之组件插槽Slot用法(组件间通信一种方式)
前端·javascript·vue.js
GISer_Jing8 小时前
【React】增量传输与渲染
前端·javascript·面试