gpt4 book ai didi

d3.js - 用 SI 前缀格式化数字,固定小数位数

转载 作者:行者123 更新时间:2023-12-04 03:44:58 25 4
gpt4 key购买 nike

我正在查看 d3.format 的可用类型

The available type values are:

exponent ("e") - use Number.toExponential.

general ("g") - use Number.toPrecision.

fixed ("f") - use Number.toFixed.

integer ("d") - use Number.toString, but ignore any non-integer values.

rounded ("r") - like fixed, but round to precision significant digits.

percentage ("%") - like fixed, but multiply by 100 and suffix with "%".

rounded percentage ("p") - like rounded, but multiply by 100 and suffix with "%".

SI-prefix ("s") - like rounded, but with a unit suffixed such as "9.5M" or "1.00µ".


https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format
我想要的是一个 SI 前缀,就像固定而不是四舍五入这样的格式选项是否存在?
一些例子:
var format = d3.format('.1s');
format(12600000); // Would like 12.6M get 10M
format(12400000); // Would like 12.4M get 10M
format(1240000); // Would like 1.2M get 1M
format(1290000); // Would like 1.3M get 1M

最佳答案

你几乎猜对了。使用 d3.formatPrefix() 可以得到 SI 前缀。为了得到没有小数的四舍五入数,我使用了 Javascript's .toFixed() :

var prefix = d3.formatPrefix(137594020);
console.log(prefix.symbol); // "M"
console.log(prefix.scale(137594020).toFixed()); // 138

var prefix = d3.formatPrefix(13759402);
console.log(prefix.symbol); // "M"
console.log(prefix.scale(13759402).toFixed()); // 14

var prefix = d3.formatPrefix(1375);
console.log(prefix.symbol); // "k"
console.log(prefix.scale(1375).toFixed()); // 1

您可以在 jsfiddle 自己尝试.

关于d3.js - 用 SI 前缀格式化数字,固定小数位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13828003/

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