【问题标题】:Formatting y-axis格式化 y 轴
【发布时间】:2013-07-10 14:47:34
【问题描述】:

如何将图表条 y 轴的货币值格式化为:

R$ 123.456,00

代替:

R$ 123,456.00

目前我正在使用此函数进行格式化,但无法进行这种简单的更改:

var format = d3.format(',.2f'); // Need to change this, but don't know how

chart.yAxis.tickFormat(function(d) {
    return "R$ " + format(d);
});

我已经在 D3 文档中进行了搜索,但找不到任何内容。

【问题讨论】:

    标签: d3.js nvd3.js


    【解决方案1】:

    使用 d3 5.5,您可以创建自定义语言环境

    https://github.com/d3/d3-format#formatLocale

    还要注意说明符(传递给 .format 的参数)我现在包含一个 $ 这将自动在格式化字符串中包含货币前缀。

    const customD3Locale = d3.formatLocale({
      decimal: ",",
      thousands: ".",
      grouping: [3],
      currency: ["R$",""]
    })
    
    const format = customD3Locale.format('$,.2f');
    

    【讨论】:

      【解决方案2】:

      格式方法似乎不允许自定义千位和小数分隔符。我认为您应该自己替换符号:

      var format = d3.format(',.2f');
      
      // Format the number, adding thousands and decimal separators
      var label = format(1234.00);
      
      // Replace the . and the , symbols. The ! symbol is necessary to do the swap
      // it can be other symbol though
      label = label.replace('.', '!');
      label = label.replace(',', '.');
      label = label.replace('!', ',');
      
      // The result is 'R$ 1.234,00'
      d3.select('#chart').append('p').text('R$ ' + label);
      

      这个jsfiddle 有替换代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-22
        • 2015-09-30
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        相关资源
        最近更新 更多