当前位置:   article > 正文

js 计算金额出现很多小数位_js 为什么1- (90 / 100)小数点位数那么多

js 为什么1- (90 / 100)小数点位数那么多

场景复现:在js中进行带有小数点也就是浮点数进行加减的时候有时候会出现很诡异的情况,比方说:

后来查找了一些资料,有网友在用以下简单计算的时候也会出现这种问题,如:

 

 产生原因:

JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,但并不是所有的小数点运算都会出现这种问题

解决方式:

方式1:粗暴解决,用tofixed直接抹除掉多余的位数,但是这种对精度要求不高的场景可以使用,涉及到金额计算就不能直接用了

方式2:

  1. //货币格式化
  2. formatMoney(number, places, symbol, thousand, decimal) {
  3. number = number || 0
  4. places = !isNaN((places = Math.abs(places))) ? places : 2
  5. symbol = symbol !== undefined ? symbol : '¥'
  6. thousand = thousand || ','
  7. decimal = decimal || '.'
  8. var negative = number < 0 ? '-' : '',
  9. i = parseInt((number = Math.abs(+number || 0).toFixed(places)), 10) + '',
  10. j = (j = i.length) > 3 ? j % 3 : 0
  11. return (
  12. symbol +
  13. negative +
  14. (j ? i.substr(0, j) + thousand : '') +
  15. i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) +
  16. (places ?
  17. decimal +
  18. Math.abs(number - i)
  19. .toFixed(places)
  20. .slice(2) :
  21. '')
  22. )
  23. },

使用方式:直接传入金额即可

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/184037
推荐阅读
相关标签
  

闽ICP备14008679号