如何在 D3.js /C3.js 中格式化数字

Sac*_*she 1 javascript charts d3.js c3.js

我的应用程序支持下面列出的几种数字格式,并希望以该格式显示数字 c3 图表。

NUMBER_FORMAT1="#,###.##" ( decimal separator . and thousand separator , )
NUMBER_FORMAT2="#.###,##" ( decimal separator , and thousand separator . )
NUMBER_FORMAT3="# ###,##" ( decimal separator , and thousand separator space )
NUMBER_FORMAT4="# ###.##" ( decimal separator . and thousand separator space )
Run Code Online (Sandbox Code Playgroud)

pot*_*ngs 5

您可以为此使用 d3 的格式函数(https://github.com/mbostock/d3/wiki/Formatting

var chart = c3.generate({
    data: {
        columns: [
            ['data1', 30, 200, 100, 400, 20050, 100],
        ]
    },
    tooltip: {
        format: {
            value: function(value) {
                return d3.format(",.2f")(value)
            }
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

以第一种格式提供工具提示。您可以在 C3 接受格式说明符的任何地方使用它。


小提琴 - http://jsfiddle.net/6j2hys0s/


但是,对于其他格式,您必须使用正则表达式来交换 , 和 . 用你想要的字符。

// #.###,##
return d3.format(",.2f")(value).replace('.', ' ').replace(/,/g, '.').replace(' ', ',')

// # ###,##
return d3.format(",.2f")(value).replace(/,/g, ' ').replace(/\./, ',');

// # ###.##
return d3.format(",.2f")(value).replace(/,/g, ' ');
Run Code Online (Sandbox Code Playgroud)