前端vue项目如何使用Decimal.js做加减乘除求余运算
作者:H_HX126
decimal.js是使用的二进制来计算的,可以更好地实现格化式数学运算,对数字进行高精度处理,使用decimal类型处理数据可以保证数据计算更为精确,这篇文章主要给大家介绍了关于前端vue项目如何使用Decimal.js做加减乘除求余运算的相关资料,需要的朋友可以参考下
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做加减乘除求余运算内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
