以我为例:
d3.format("~s")(656628); //656.628k
但我的预期结果:656.63k
我想使用 d3-format 选项而不是手动处理它。
最佳答案
您只需要 d3.formatPrefix
, 这...
Convert values to the units of the appropriate SI prefix for the specified numeric reference value before formatting in fixed point notation.
...,以 ".2"
作为说明符,您自己的数字作为值。
这是带有您的号码的演示:
const myNumber = 656628;
console.log(d3.formatPrefix(".2", myNumber)(myNumber));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
这给了你预期的结果:656.63k
。
并且,为了完整起见,还有一些其他数字:
[1232, 7676546655, 665, 0.0012, 8887878].forEach(function(d) {
console.log("Number: " + d + " - Your format: " + d3.formatPrefix(".2", d)(d))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
关于javascript - 如何使用格式 SI 前缀四舍五入到小数点后两位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55608134/