提示:学习express,搭建管理系统
文章目录
- 前言
- 一、转换成整数计算后再转换成小数
- 二、toFixed
- 三、math.js
- 四、bignumber.js
- 五、big.js
- 总结
前言
原始计算
let aNum = 6.6 + 0.3;let bNum = 6.6 - 0.2;let cNum = 6.6 * 0.3;let dNum = 6.6 / 0.2;console.log(aNum,bNum,cNum,dNum,'normal');
一、转换成整数计算后再转换成小数
//乘以小数点后保留的位数的倍数
let multipleNum = 100;aNum = (Math.round(6.6*multipleNum + 0.3*multipleNum))/multipleNum;bNum = (Math.round(6.6*multipleNum - 0.2*multipleNum))/multipleNum;cNum = (Math.round(6.6 * 0.3 * multipleNum))/multipleNum;dNum = (Math.round((6.6 / 0.2) * multipleNum))/multipleNum;console.log(aNum,bNum,cNum,dNum,'multipleNum');
二、toFixed
Number.toFixed会返回String类型
//toFixed四舍五入保留几位小数 并且把number类型转成string类型
aNum = parseFloat((6.6+0.3).toFixed(2));
bNum = parseFloat((6.6-0.2).toFixed(2));
cNum = parseFloat((6.6*0.3).toFixed(2));
dNum = parseFloat((6.6/0.2).toFixed(2));
console.log(aNum,bNum,cNum,dNum,'toFixed');
三、math.js
npm install mathjs --save-dev
aNum = math.add(math.bignumber(6.6), math.bignumber(0.3));
bNum = math.subtract (math.bignumber(6.6), math.bignumber(0.2));
cNum = math.multiply(math.bignumber(6.6), math.bignumber(0.3));
dNum = math.divide(math.bignumber(6.6), math.bignumber(0.2));
console.log(aNum.toNumber(),bNum.toNumber(),cNum.toNumber(),dNum.toNumber(),'math bignumber toNumber');console.log(parseFloat(aNum.toString()),parseFloat(bNum.toString()),parseFloat(cNum.toString()),parseFloat(dNum.toString()),'math bignumber toString');console.log(parseFloat(math.format(aNum)),parseFloat(math.format(bNum)),parseFloat(math.format(cNum)),parseFloat(math.format(dNum)),'math bignumber format');
git地址
math.js官网
四、bignumber.js
npm install bignumber.js --save-dev
let num = new BigNumber(6.6);
aNum = num.plus(0.3);
bNum = num.minus(0.2);
cNum = num.multipliedBy(0.3);
dNum = num.dividedBy(0.2);
console.log(aNum.toNumber(),bNum.toNumber(),cNum.toNumber(),dNum.toNumber(),'bignumber.js toNumber');console.log(parseFloat(aNum.toString()),parseFloat(bNum.toString()),parseFloat(cNum.toString()),parseFloat(dNum.toString()),'bignumber.js toString');console.log(parseFloat(aNum.toFormat()),parseFloat(bNum.toFormat()),parseFloat(cNum.toFormat()),parseFloat(dNum.toFormat()),'bignumber.js toFormat');
git地址
五、big.js
npm install big.js --save-dev
let num0 = new Big(6.6);
aNum = num0.add(0.3);
bNum = num0.minus(0.2);
cNum = num0.times(0.3);
dNum = num0.div(0.2);
console.log(aNum.toNumber(),bNum.toNumber(),cNum.toNumber(),dNum.toNumber(),'big.js toNumber');console.log(parseFloat(aNum.toString()),parseFloat(bNum.toString()),parseFloat(cNum.toString()),parseFloat(dNum.toString()),'big.js toString');
git地址
总结
踩坑路漫漫长@~@