Format a number with SI Prefix, with fixed number of decimals
Asked Answered
C

2

13

I'm looking over the available type for 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

What I would like is an SI-prefix that is like fixed not rounded does such a format option exist?

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
Commentative answered 11/12, 2012 at 20:30 Comment(0)
T
12

You almost got it right. Using d3.formatPrefix() one can get the SI prefix. To get the rounded number without decimals, I used 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

You can try it yourself at jsfiddle.

Torus answered 18/2, 2013 at 18:5 Comment(2)
Any idea how this could be accomplished in d3 v4 ?Argentite
This is working for me in d3 v4 to get a fixed point with SI prefix: value = 238489000; console.log(d3.formatPrefix('.1f', value)(value)); // 238.5Shaun
G
0

You only need to change your

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>
Gangplank answered 22/6, 2016 at 0:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.