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做加减乘除求余运算内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论