d3.format() for number abbreviations (similar to SI-prefix)
See original GitHub issueI’m wondering if anyone else would find a use for a feature like this. For example, SI-prefix will condense large (or small) numbers and add the appropriate metric system character:
var parse = d3.format("s");
console.log(parse(5000000000)); //5G
console.log(parse(5000000)); //5M
console.log(parse(.0005)); //500µ
I want to create a similar function, let’s just call it d3.format("a")
that will condense numbers to human readable abbreviations, so long numbers are more easily inserted into charts and axes.
var parse = d3.format("a");
console.log(parse(5000000000)); //5B
console.log(parse(5000000)); //5M
console.log(parse(5000)); //500k
Possible prefixes could be ‘T’ for trillion, ‘B’ for billion, ‘M’ for million, ‘k’ for thousand, plus any others we may need. I don’t mind writing the functionality if @mbostock thinks it’s a good idea. I know the argument against it is to just convert the number yourself, but then the prefix isn’t being decided in real time, or you’d have to have a lot of separate if/else cases.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:10
- Comments:6 (1 by maintainers)
Top GitHub Comments
Hmm. One way you could do this would be to remap the SI prefix after invoking the format. For example:
(Note, that’s 5.00k, not 500k as in your example. I think 5.00k is correct?)
Another way might be to localize the list of SI prefixes, rather than having a
prefixes
global. (See src/locale.js in d3-format.) But, do you really want to specify the full list of 17 prefixes this way? Seems like you only care about 3 or 4… assuming you are dealing with dollar amounts, say, and not arbitrary numbers.The other simple thing you can do is to just roll your own conditional format.
I mean, yeah, your formatAbbreviation has to deal with rounding and is hard-coded to zero decimal places (in this case), but you can probably guess how to improve that if you need it… or look at how formatPrefix is implemented.
For those who are looking for a solution. We replaced .tickFormat(d3.dormat(“s”)); with the following function: .tickFormat (function (d) { return formatValue(d).replace(‘G’, ‘B’); }); Worked like a charm!