前端vue项目使用Decimal.js做加减乘除求余运算
本文介绍了如何在Vue项目中安装并使用Decimal.js库进行加、减、乘、除和求余等精确数值运算,以及注意事项:运算结果为Decimal对象需转换为数字。
安装Decimal
npm install decimal.js
引用
import Decimal from 'decimal.js'
使用
注意:运算结果是Decimal对象,需要使用.toNumber()转为数字
加 add
import Decimal from 'decimal.js'
const num1 = new Decimal(0.1);
const num2 = new Decimal(0.2);
const remainder = num1.add(num2).toNumber(); //0.3
console.log(remainder);
减 sub
import Decimal from 'decimal.js'
const num1 = new Decimal(5);
const num2 = new Decimal(3);
const remainder = num1.sub(num2).toNumber(); //2
console.log(remainder);
乘 mul
import Decimal from 'decimal.js'
const num1 = new Decimal(5);
const num2 = new Decimal(3);
const remainder = num1.mul(num2).toNumber(); //15
console.log(remainder);
除 div
import Decimal from 'decimal.js'
const num1 = new Decimal(5);
const num2 = new Decimal(3);
const remainder = num1.div(num2).toNumber(); //1.6666666666666667
const remainder1 = num1.div(num2).toNumber().toFixed(2); //1.67 保留两位
console.log(remainder);
求余 modulo
import Decimal from 'decimal.js'
const num1 = new Decimal(5);
const num2 = new Decimal(3);
const remainder = num1.modulo(num2).toNumber() //2
console.log(remainder);
原文地址:https://blog.csdn.net/m0_68716504/article/details/143058846
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!