Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a (custom) thousand separator in D3?

I'm working with D3Plus and D3Plus accepts any D3 method.

I could manage to remove decimals. What I cannot do is adding a '.' as a thousand separator instead of a ',' (in spanish 1.000.000 is 'one million') and this is for a spanish-speaking audience.

This is the relevant part of my code

"number": function(number, params) {
    var formatted = d3plus.number.format(number, params);
      if (params.key === "encuentros") {
        return d3.round(number,0);
      }
      if (params.key === "poblacion") {
        return d3.round(number,0);
      }
      else {
        return formatted;
      }
  }

I did try return d3.round(number,0) + d3.format('.') but that does not work.

The chart is "ok" but without decimal separator.

enter image description here

like image 746
pachadotdev Avatar asked Jul 05 '16 18:07

pachadotdev


1 Answers

Have you tried using d3.locale? It would work great for your use case because it builds the formatting functions based on your own localization rules.

What you can do is create custom localization rules that give your format:

var myLocale = {
  "thousands": ".",  // specify that thousands are separated with a dot
  // .. other rules
}

And then use those rules to initialize your custom formatter:

var localeFormatter = d3.locale(myLocale);
// ',.2r' means grouped thousands with two significant digits. 
// By default ',' means 'thousands' but we switched that into a '.' in our custom localization
var myFormatter = localeFormatter.numberFormat(',.2r'); 
var value = myFormatter(1000000); // "1.000.000"

Here's a running example:

// custom localization options
var myLocale = {
  "decimal": ".",
  "thousands": ".",
  "grouping": [3],
  "currency": ["$", ""],
  "dateTime": "%a %b %e %X %Y",
  "date": "%m/%d/%Y",
  "time": "%H:%M:%S",
  "periods": ["AM", "PM"],
  "days": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  "shortDays": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  "months": ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
  "shortMonths": ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"]

}

// create custom locale formatter from the given locale options
var localeFormatter = d3.locale(myLocale);

// create a formatter for the number (grouped thousands with two significant digits). By default ',' means 'thousands' but we switched that into a '.' in our custom localization
var numberFormat = localeFormatter.numberFormat(",.2r");

// test
console.log(numberFormat(1000000)); // "1.000.000"
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
like image 89
nem035 Avatar answered Sep 22 '22 13:09

nem035