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>
相关推荐
八了个戒30 分钟前
「数据可视化 D3系列」入门第三章:深入理解 Update-Enter-Exit 模式
开发语言·前端·javascript·数据可视化
胚芽鞘6811 小时前
vue + element-plus自定义表单验证(修改密码业务)
javascript·vue.js·elementui
小陈同学呦2 小时前
聊聊双列瀑布流
前端·javascript·面试
键指江湖2 小时前
React 在组件间共享状态
前端·javascript·react.js
烛阴2 小时前
零基础必看!Express 项目 .env 配置,开发、测试、生产环境轻松搞定!
javascript·后端·express
诸葛亮的芭蕉扇3 小时前
D3路网图技术文档
前端·javascript·vue.js·microsoft
徐小夕3 小时前
花了2个月时间研究了市面上的4款开源表格组件,崩溃了,决定自己写一款
前端·javascript·react.js
拉不动的猪4 小时前
UniApp金融理财产品项目简单介绍
前端·javascript·面试
萌萌哒草头将军4 小时前
😡😡😡早知道有这两个 VueRouter 增强插件,我还加什么班!🚀🚀🚀
前端·vue.js·vue-router
苏卫苏卫苏卫4 小时前
【Vue】案例——To do list:
开发语言·前端·javascript·vue.js·笔记·list