Search code examples
javascriptd3.jslocalizationdecimal-point

Replace the decimal dot with a comma on an axis in D3?


This is about the ticks on axes in D3: Is there a way to replace the decimal dot with a comma in numbers? I want the numbers to be displayed like this (which is normal in Germany, such a big number is just for demonstration)

1.000.000,1 // This is one million and a tenth

and not like this:

1,000,000.1

I've read the documentation about the topic, but it seems like there is no possibility!? That's my relevant code so far:

localeFormatter = d3.locale({
                "decimal": ".",
                "thousands": ",",
                "grouping": [3],
                "currency": ["", "€"],
                "dateTime": "%a, %e %b %Y, %X",
                "date": "%d.%m.%Y",
                "time": "%H:%M:%S",
                "periods": ["", ""],
                "days": ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"],
                "shortDays": ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
                "months": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
                "shortMonths": ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"]
            });


numberFormat = localeFormatter.numberFormat("04.,"); // The setting is applied, but has not the desired effect...

yAxis = d3.svg.axis()
                .scale(y)
                .orient("left")
                .tickFormat(numberFormat);

Solution

  • Using the following settings for d3.locale:

    var localeFormatter = d3.locale({
          "decimal": ",",
          "thousands": ".",
          ...
        });
    

    Note that I have changed the . in , and vice versa. And with:

    var numberFormat = localeFormatter.numberFormat(",.2f"); 
    

    I print the number using a thousands separator , (it uses a . as defined in the locale) and two digits after the comma .2f:

    console.log(numberFormat(1000000.1)); // "1.000.000,10"