Search code examples
d3.jslocalenumber-formatting

d3 custom number formatting


How can I select a custom thousand and decimal separators using d3? Ie., The input number is 221343.455. The output should be 221 343,455

It does not seem to be trivial, since there is this option to choose whether a comma should be the separator or not.

Edit #1: d3 should be used since I am using a chart library which gets d3 format to process one of the axis' ticks

Edit #2: I am tied to this version v3.5.0 of d3

Thanks in advance.


Solution

  • You need two things for this to work:

    1. A custom locale object setting the grouping and decimal separator:

      var locale = d3.formatLocale({
        decimal: ",",
        thousands: " ",
        grouping: [3]
      });
      
    2. A format specifier which makes use of these separators:

      var format = locale.format(",.3f");
      

    Have a look at the following snippet for a working demo:

    var locale = d3.formatLocale({
      decimal: ",",
      thousands: " ",
      grouping: [3]
    });
    
    var format = locale.format(",.3f");
    
    console.log(format(221343.455));   // 221 343,455
    <script src="https://d3js.org/d3.v4.js"></script>