场景复现:在js中进行带有小数点也就是浮点数进行加减的时候有时候会出现很诡异的情况,比方说:
后来查找了一些资料,有网友在用以下简单计算的时候也会出现这种问题,如:
产生原因:
JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,但并不是所有的小数点运算都会出现这种问题
解决方式:
方式1:粗暴解决,用tofixed直接抹除掉多余的位数,但是这种对精度要求不高的场景可以使用,涉及到金额计算就不能直接用了
方式2:
//货币格式化
formatMoney(number, places, symbol, thousand, decimal) {
number = number || 0
places = !isNaN((places = Math.abs(places))) ? places : 2
symbol = symbol !== undefined ? symbol : '¥'
thousand = thousand || ','
decimal = decimal || '.'
var negative = number < 0 ? '-' : '',
i = parseInt((number = Math.abs(+number || 0).toFixed(places)), 10) + '',
j = (j = i.length) > 3 ? j % 3 : 0
return (
symbol +
negative +
(j ? i.substr(0, j) + thousand : '') +
i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) +
(places ?
decimal +
Math.abs(number - i)
.toFixed(places)
.slice(2) :
'')
)
},
使用方式:直接传入金额即可