是否有基于 Math.round 而不是 Number.toFixed 的 d3.format 替代方案? 我喜欢 d3.format,但它不会像人们通过科学或其他舍入约定所期望的那样舍入 0.05(请参阅https://github.com/d3/d3-format/issues/27)
目前 d3.format 在内部使用
Number.toFixed
而不是 Math.round
,这会导致意外舍入 https://github.com/d3/d3-format/issues/89
所以有时 0.05 向下舍入 (
8.95=>8.9
),有时向上舍入 (2.95=>3.0
),但它不遵循“四舍五入”等标准科学规则,而是基于二进制表示法
[0.95,1.95,2.95,3.95,4.95,5.95,6.95,7.95,8.95,9.95]
returns
['0.9', '1.9', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '8.9', '9.9']
因为
[0.95,1.95,2.95,3.95,4.95,5.95,6.95,7.95,8.95,9.95].map(v=>v.toFixed(16))
returns
0: "0.9500000000000000"
1: "1.9500000000000000"
2: "2.9500000000000002"
3: "3.9500000000000002"
4: "4.9500000000000002"
5: "5.9500000000000002"
6: "6.9500000000000002"
7: "7.9500000000000002"
8: "8.9499999999999993"
9: "9.9499999999999993"
试试这个:
const round = (num, digits) => {
const multiplier = Math.pow(10, digits);
const value = Math.round(num * multiplier) / multiplier;
return value.toFixed(digits);
}
console.log(round(3.14159265359, 3));
console.log(round(2.7182818284, 2));