aitor
aitor

Reputation: 2735

d3.js. To show dataset number in locale format

I have a dataset array of numbers:

var dataset = [ 2147000, 3750000, 3434000, 3095000, 8132000, 8875000, 7727000, 6605000 ];

And locale definition:

var ES = d3.locale (…)

I have this code for render dataset:

svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .text(function(d) {
      return d;
    })

I want to show the numbers in locale format but I dont know how to tell it to function(d)

This is a codepen working. I want to show in local format the tags inside bars. (line 65) http://codepen.io/aitormendez/pen/xRVNMb?editors=0010

I tried ES.numberFormat("$,.")

Thanks in advance.

Upvotes: 1

Views: 162

Answers (1)

Cleared
Cleared

Reputation: 2590

ES.numberFormat("$,.") that you use as tickFormat is a function, and given an argument (a number) it will return a formatted string given the specified format. So you format the number 1000000 you simply use the function by calling ES.numberFormat("$,.")(d)(1000000).

To implement in your code:

svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .text(function(d) {
      return ES.numberFormat("$,.")(d);
    })

An even better way would be to declare the function as

var nbrFormat = ES.numberFormat("$,.");

And then use

.tickFormat(nbrFormat);

and

return nbrFormat(d);

To limit your declaration of the format to one place, instead of two.

See https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md

Upvotes: 2

Related Questions