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>
相关推荐
楚轩努力变强1 小时前
前端工程化常见问题总结
开发语言·前端·javascript·vue.js·visual studio code
前端开发爱好者2 小时前
只有 7 KB!前端圈疯传的 Vue3 转场动效神库!效果炸裂!
前端·javascript·vue.js
Fly-ping2 小时前
【前端】JavaScript文件压缩指南
开发语言·前端·javascript
接口写好了吗2 小时前
【el-table滚动事件】el-table表格滚动时,获取可视窗口内的行数据
javascript·vue.js·elementui·可视窗口滚动
未来之窗软件服务3 小时前
免费版酒店押金原路退回系统之【房费押金计算器】实践——仙盟创梦IDE
前端·javascript·css·仙盟创梦ide·东方仙盟·酒店押金系统
云边散步4 小时前
《校园生活平台从 0 到 1 的搭建》第四篇:微信授权登录前端
前端·javascript·后端
讨厌吃蛋黄酥4 小时前
React样式冲突终结者:CSS模块化+Vite全链路实战指南🔥
前端·javascript·react.js
星眠4 小时前
学习低代码编辑器第四天
javascript·面试
Hilaku4 小时前
原生<dialog>元素:别再自己手写Modal弹窗了!
前端·javascript·html
GISer_Jing4 小时前
Coze:字节跳动AI开发平台功能和架构解析
javascript·人工智能·架构·开源