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

审核中 分享 未结
0 94
xcc
xcc 2019-03-21 11:20:43
悬赏:0飞吻
策略就是把小数值变成整数进行操作加减乘除 [pre] // 获取最大补位长度 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 }; [/pre] 转载自: a(https://segmentfault.com/a/1190000018592152)[https://segmentfault.com/a/1190000018592152]
回帖
  • 消灭零回复
热议榜单
我是QQ新户 2
1024程序员节 - Happy 1024. 1
ieJSON

微信扫码关注 ieJSON 公众号