Skip to content

Number formatting in D3.js

Pavel Rodionov edited this page May 1, 2018 · 1 revision

Number formatting

For full details on formatting in D3 follow this link

When we display influence score in a bubble, we have to round it up first. This is the piece of code that we use

precision = d3.precisionFixed(0.1);
format = d3.format("." + this.precision + "f");
...
//below we format the score before displaying it
.text(d => ` ${this.format(d.score)}`)

What are exactly d3.precisionFixed() and d3.format() and why we should use two in combination?

Formatting numbers for human consumption is the purpose of d3-format

  • d3.format(specifier) An alias for locale.format on the default locale This does not explain much really:

  • locale.format(specifier) Returns a new format function for the given string specifier. The returned function takes a number as the only argument, and returns a string representing the formatted number. The general form of a specifier is: [[fill]align][sign][symbol][0][width][,][.precision][type]

in our example: format = d3.format("." + this.precision + "f"); we use type value f, which stands for fixed point notation. It displays the number as a fixed-point number.

  • d3.precisionFixed(step) Returns a suggested decimal precision for fixed point notation given the specified numeric step value. The step represents the minimum absolute difference between values that will be formatted.

In our example, we use step 0.1. If I am correct, that means we round a number to one decimal point.

Interestingly, that when we use fixed point notation, we don't just set up a number of decimal points but we have to specify the precision instead. It may come a little counter intuitive at first.

Clone this wiki locally