Skip to content

Add any string suffix to number.  #121

Closed

Description

@inesmoskal

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".

Activity

  1. mbostock commented on Aug 5, 2021

    @mbostock
    Member

    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`);
  2. mbostock commented on Jan 14, 2026

    @mbostock
    Member

    This was secretly added in #135. You can now pass an options second argument to d3.format that accepts a suffix (and prefix). For example:

    d3.format("d", {suffix: "°C"})(25) // "25°C"

    The advantage of this approach over the above wrappers is that it works correctly with respect to some of the more advanced formatting directives, such as parentheses for negative numbers.

    d3.format("(d", {suffix: "°C"})(-25) // "(25°C)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions