如何优雅解决 js小数点计算错误问题(三个函数告诉你解决办法)

31次阅读

共计 865 个字符,预计需要花费 3 分钟才能阅读完成。

策略就是把小数值变成整数进行操作加减乘除
// 获取最大补位长度
const findMinRadixPoint = (numberList) => {
let maxLg = 0;
numberList.forEach(num => {
let numStr = num.toString();
let numSplit = numStr.split(‘.’);
let bitLg = (numSplit[1] || ”).length;
(bitLg > maxLg) && (maxLg = bitLg)
});
return maxLg
};

/* 数字补位 */
const numberCoverPosition = (number, length) => {
let numberStr = String(number);
let lg = numberStr.length;
let idx = numberStr.indexOf(‘.’);
if (idx === -1) {
return number * Math.pow(10, length);
} else {
let addW = length – (lg – 1 – idx);
let oLoop = ”;
while (addW) {
oLoop += ‘0’;
addW–;
}
return Number(numberStr.replace(/(\d+?)\.(\d+?)/, `$1$2${oLoop}`))
}
};
/* 数字减位 */
const NumberDigitAbsorption = (number, length) => {
let numberStr = String(number);
let lg = numberStr.length;

if (lg > length) {
numberStr = numberStr.substr(0, lg – length) + ‘.’ + numberStr.substr(lg – length);
} else {
let leftW = length – lg;
let oLoop = ”;
while (leftW) {
oLoop += ‘0’;
leftW–;
}
numberStr = ‘0.’ + oLoop + numberStr
}
return numberStr
};

正文完
 0