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 分钟前
React事件处理全解析
开发语言·前端·javascript·react.js·前端框架
英俊潇洒美少年12 分钟前
豆包官方开放 API 调用指南(合法稳定版)
前端·javascript
漠月瑾-西安15 分钟前
JavaScript 字符串处理技巧:substring 与 indexOf 的灵活组合
javascript·前端开发·indexof·代码优化·substring·字符串处理
Mintopia17 分钟前
React vs Vue 优势对比Demo(证明React更具优势)
前端·vue.js·react.js
海上彼尚22 分钟前
Nuxt4 官网访问来源统计的实现
开发语言·前端·javascript
三*一24 分钟前
mapbox 基于 Turf.js 实现高精度多边形分割(支持带空洞 / 坐标无损)
开发语言·前端·javascript·vue.js·mapbox gl
漂移的电子32 分钟前
【常用】element-ui/moment.js/echarts.js等
javascript·ui·echarts
姓蔡小朋友41 分钟前
Agent Skill设计模式
开发语言·javascript·设计模式
yaaakaaang1 小时前
(五)前端,如此简单!---变量
前端·javascript
2501_941982051 小时前
企微私域:实现企业通讯工具外部群消息的自动化主动推送
java·前端·javascript