封装toPrecision方法,处理js精度丢失问题

153 阅读1分钟
function toPrecision(num, precision = 2) {
  // 精度倍数
  const precisionPercent = Math.pow(10, precision)
  // 四舍五入取整
  const integerVal = Math.round(num * precisionPercent)
  const value = parseFloat(integerVal / precisionPercent)
  return value.toFixed(precision);
}
0.1+0.2 // 0.30000000000000004
toPrecision(0.1 + 0.2) // '0.30'