当前位置: 代码网 > it编程>编程语言>Javascript > 前端vue项目如何使用Decimal.js做加减乘除求余运算

前端vue项目如何使用Decimal.js做加减乘除求余运算

2024年06月11日 Javascript 我要评论
1 vue项目安装decimalnpm install decimal.js2 注意运算结果是decimal对象,需要使用.tonumber()转为数字3 加 addconst decimal = r

1 vue项目安装decimal

npm install decimal.js

2 注意

运算结果是decimal对象,需要使用.tonumber()转为数字

3 加 add

const decimal = require('decimal.js')
const num1 = decimal("5");
const num2 = decimal("3");
const remainder = num1.add(num2);

4 减 sub

const decimal = require('decimal.js')
const num1 = decimal("5");
const num2 = decimal("3");
const remainder = num1.sub(num2);

5 乘 mul

const decimal = require('decimal.js')
const num1 = decimal("5");
const num2 = decimal("3");
const remainder = num1.mul(num2);

6 除 div

const decimal = require('decimal.js')
const num1 = decimal("5");
const num2 = decimal("3");
const remainder = num1.div(num2);

7 求余 modulo

const decimal = require('decimal.js')
const num1 = decimal("5");
const num2 = decimal("3");
const remainder = num1.modulo(num2);

附:vue 使用decimal.js 解决小数相加合计精确度丢失问题

  • 安装依赖 decimal.js
    • npm install --save decimal.js
  • 封装
    • 在utils文件夹下创建decimal.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()
}
  • 页面使用
<script>
  import {add} from "@/utils/decimal"
  export default {
    methods:{
      handleplus() {
        add(10.5,4.877)
      }
    }
  }
</script>

总结 

到此这篇关于前端vue项目如何使用decimal.js做加减乘除求余运算的文章就介绍到这了,更多相关vue decimal.js做加减乘除求余运算内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com