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

6

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

我已经成功地去掉了小数部分。但我无法添加一个'.'作为千位分隔符,而不是','(在西班牙语中,1000000是'一百万'),这是为西班牙语听众准备的。

以下是我代码的相关部分:

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

图表“还行”,但没有小数分隔符。

输入图片描述

4个回答

10

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


非常感谢!这是一个非常好的方法。我现在正在适应它。 - pachadotdev

2

0

我觉得您在寻找的是 D3.numberFormat(",d")


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接