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>
相关推荐
计算机学姐3 小时前
基于微信小程序的高校班务管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
哆啦A梦15887 小时前
点击Top切换数据
前端·javascript·vue.js
小光学长8 小时前
基于Vue的2025年哈尔滨亚冬会志愿者管理系统5zqg6m36(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
@PHARAOH8 小时前
WHAT - 受控组件和非受控组件
前端·javascript·react.js
麦麦大数据9 小时前
D027 v2 vue+django+neo4j 基于知识图谱红楼梦问答系统 (新增问关系功能;新增知识节点和关系管理功能,neo4j增删改查功能)
vue.js·django·问答系统·知识图谱·neo4j·图谱管理·neo4j增删改查
专注前端30年9 小时前
【JavaScript】reduce 方法的详解与实战
开发语言·前端·javascript
菜鸟una10 小时前
【瀑布流大全】分析原理及实现方式(微信小程序和网页都适用)
前端·css·vue.js·微信小程序·小程序·typescript
专注前端30年11 小时前
2025 最新 Vue2/Vue3 高频面试题(10月最新版)
前端·javascript·vue.js·面试
Highcharts.js11 小时前
选择合适的组合:如何打造数据可视化的“黄金组合”
javascript·信息可视化·highcharts·交互式图表开发
angelQ12 小时前
Vue 3 中 ref 获取 scrollHeight 属性为 undefined 问题定位
前端·javascript