toFixed 的诡异行为
日常开发难免会遇到处理小数,四舍五入,通常我们所知最简单的方法就是使用 toFixed。但经过本人测试,toFixed 不是四舍五入且无直观的规律,也不是网上流传的银行家计数法,不适用我们日常使用。感兴趣可查看ecma 文档对其的解释
诡异现象
console.log('0.15 toFixed(1) => ', (0.15).toFixed(1)) // 0.1 weird
console.log('0.25 toFixed(1) => ', (0.25).toFixed(1)) // 0.3
console.log('0.35 toFixed(1) => ', (0.35).toFixed(1)) // 0.3 weird
console.log('0.45 toFixed(1) => ', (0.45).toFixed(1)) // 0.5
console.log('0.55 toFixed(1) => ', (0.55).toFixed(1)) // 0.6
console.log('0.65 toFixed(1) => ', (0.65).toFixed(1)) // 0.7
console.log('0.75 toFixed(1) => ', (0.75).toFixed(1)) // 0.8
console.log('0.85 toFixed(1) => ', (0.85).toFixed(1)) // 0.8 weird
console.log('0.95 toFixed(1) => ', (0.95).toFixed(1)) // 0.9 weird
console.log('1.15 toFixed(1) => ', (1.15).toFixed(1)) // 1.1 weird
console.log('1.25 toFixed(1) => ', (1.25).toFixed(1)) // 1.3
console.log('1.35 toFixed(1) => ', (1.35).toFixed(1)) // 1.4
console.log('1.45 toFixed(1) => ', (1.45).toFixed(1)) // 1.4 weird
console.log('1.55 toFixed(1) => ', (1.55).toFixed(1)) // 1.6
console.log('1.65 toFixed(1) => ', (1.65).toFixed(1)) // 1.6 weird
console.log('1.75 toFixed(1) => ', (1.75).toFixed(1)) // 1.8
console.log('1.85 toFixed(1) => ', (1.85).toFixed(1)) // 1.9
console.log('1.95 toFixed(1) => ', (1.95).toFixed(1)) // 1.9 weird
console.log('2.15 toFixed(1) => ', (2.15).toFixed(1)) // 2.1 weird
console.log('2.25 toFixed(1) => ', (2.25).toFixed(1)) // 2.3
console.log('2.35 toFixed(1) => ', (2.35).toFixed(1)) // 2.4
console.log('2.45 toFixed(1) => ', (2.45).toFixed(1)) // 2.5
console.log('2.55 toFixed(1) => ', (2.55).toFixed(1)) // 2.5 weird
console.log('2.65 toFixed(1) => ', (2.65).toFixed(1)) // 2.6 weird
console.log('2.75 toFixed(1) => ', (2.75).toFixed(1)) // 2.7 weird
console.log('2.85 toFixed(1) => ', (2.85).toFixed(1)) // 2.8 weird
console.log('2.95 toFixed(1) => ', (2.95).toFixed(1)) // 3.0
解决方法
import { round } from 'mathjs'
round(0.055, 1) // 0.1
round(0.155, 1) // 0.2
round(0.255, 1) // 0.3
round(0.355, 1) // 0.4
round(0.455, 1) // 0.5
round(0.555, 1) // 0.6
round(0.655, 1) // 0.7
round(0.755, 1) // 0.8
round(0.855, 1) // 0.9
round(0.955, 1) // 1