d3-format icon indicating copy to clipboard operation
d3-format copied to clipboard

Add any string suffix to number.

Open inesmoskal opened this issue 4 years ago • 1 comments

I know there is the possibility to add the currency suffix, but it would be useful to be able to add a more flexible suffix. For example "°C" for temperature values or "kg".

inesmoskal avatar Aug 05 '21 07:08 inesmoskal

For a fixed suffix, the recommended way is to wrap the format function. For example:

const formatNumber = d3.format("d"); 
const formatCelsius = d => `${formatNumber(d)}°C`;

You can also combine the two like so:

const formatCelsius = (f => d => `${f(d)}°C`)(d3.format("d"));

We could perhaps formalize this pattern as:

const formatCelsius = d3.format("d", (f, d) => `${f(d)}°C`);

Or maybe make the arguments order-dependent to allow pre- (e.g., multiplying by 100) and post-formatting:

const formatCelsius = d3.format("d", s => `${s}°C`);

mbostock avatar Aug 05 '21 13:08 mbostock