繁体   English   中英

如何在D3中添加(自定义)千位分隔符?

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

我正在使用D3Plus,D3Plus接受任何D3方法。

我可以设法删除小数。 我不能做的是添加'。' 作为一个千分词而不是','(西班牙语1.000.000是'一百万')这是一个讲西班牙语的观众。

这是我的代码的相关部分

"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('.')但这不起作用。

图表是“ok”但没有小数点分隔符。

在此输入图像描述

你尝试过使用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> 

D3plus不是自定义数字格式化程序的复杂性,而是内置了本地化,包括一个用于西班牙语的本地化。 这不仅可以处理数字格式,还可以将任何接口消息转换为该语言。 您必须添加到可视化中的是:

.format("es_ES")

以下是D3plus网站上的一个示例: http ://d3plus.org/examples/advanced/10bfe1908a200c201145/

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

查看d3plus的源代码,特别是数字格式库: https//github.com/alexandersimoes/d3plus/blob/master/src/number/format.coffee

您可以在此处尝试实现的示例: http//d3plus.org/examples/advanced/7760febcda3375b39e1f/

特别是,请查看format()方法(第29-39行)。

我想你正在寻找D3.numberFormat(",d")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM