Format number with prefix SI, with a fixed number of decimal places

I am looking at an accessible type for d3.format

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") - as fixed, but rounded to exact significant digits.

percent ("%") - as fixed, but multiplied by 100 and a suffix with "%".

rounded percentage ("p") - as rounded, but multiplied by 100 and the suffix with "%".

SI prefix ("s") - as rounded , but with a suffix, for example, "9.5M" or "1.00ΞΌ".

https://github.com/mbostock/d3/wiki/Formatting#wiki-d3_format

I would like a SI prefix like fixed, not rounded, does this format have a format?

Some examples:

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 
+8
source share
2 answers

You understand almost everything. Using d3.formatPrefix() , you can get the SI prefix. To get a rounded number without decimals, I used Javascript .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 

You can try it yourself: jsfiddle .

+9
source share

You only need to change

 d3.format('.1s'); 

by

 d3.format('.3s'); 

 console.log(d3.format(".3s")(12600000)); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
0
source share

All Articles