2016-07-05 42 views
2

我正在与D3Plus和D3Plus接受任何D3方法。如何在D3中添加(自定义)千分隔符?

我可以设法删除小数。我不能做的是添加'。'作为千位分隔符而不是','(西班牙语1.000.000是'100万'),这是给西班牙语的听众。

这是我的代码的相关部分

"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; 
     } 
    } 

我也尝试return d3.round(number,0) + d3.format('.')但不起作用。

图表为“好”,但没有小数点分隔符。

enter image description here

回答

6

您是否尝试过使用d3.locale?它对您的用例非常有用,因为它会根据您自己的本地化规则构建格式化函数。

你可以做的是创造,让您的格式自定义的本地化规则:

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

,然后使用这些规则来初始化您的自定义格式:

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" 

这里是一个正在运行的例子:

// 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>

+0

非常感谢!这是一个很好的方法。我正在适应它。 – pachamaltese

+0

很高兴帮助:) – nem035

2

D3plus不是定制数字格式器的复杂性,而是内置了本地化版本,其中包括一个用于西班牙语的版本。这不仅关注数字格式,而且还将任何接口消息转换为该语言。所有你必须添加到您的可视化是这样的:

.format("es_ES") 

这里的D3plus网站上的例子:http://d3plus.org/examples/advanced/10bfe1908a200c201145/

而这里的支持本地化的列表:https://github.com/alexandersimoes/d3plus/wiki/Localization