gpt4 book ai didi

javascript - 将长数字格式化为 K 和 2 位有效数字

转载 作者:行者123 更新时间:2023-11-30 19:31:18 24 4
gpt4 key购买 nike

我有以下数字,我想将其格式化为更简洁的长度以显示在图例上

1000000
1200
321
2
0.31243
0.011231132

如下

100K
1.2K
321
2
0.31
0.01

我尝试使用内置的 d3 格式化函数来解决这个问题

d3.format(".2s")

但是它的输出是

100k
1.2k
321
2
30m
100m

我认为问题在于 s 标识符与 SI 单位相关,这符合我的要求,除非数字低于 1。我如何将其格式化为我所期望的

因为我正在使用 tickFormat(d3.format(".2s")); 我需要格式函数与 tickFormat 期望的格式相同

最佳答案

在我看来,您想避免为约数添加 SI 前缀。如果这是正确的,只需检查值是否大于 1 以应用格式就足够了:

[1000000, 1200, 321, 2, 0.31243, 0.011231132].forEach(d => {
d > 1 ? console.log(d3.format(".2s")(d)) : console.log(d3.format(".2")(d))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

关于javascript - 将长数字格式化为 K 和 2 位有效数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com