2016-07-05 75 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