Chart.js数字格式 [英] Chart.js number format
问题描述
我浏览了 Chart.js文档,没有找到任何关于数字格式的信息
ie)1,000.02从数字格式#,###。00
I went over the Chart.js documentation and did not find anything on number formatting ie) 1,000.02 from number format "#,###.00"
我也做了一些基本测试,似乎图表不接受非数值文本的值
I also did some basic tests and it seems charts do not accept non-numeric text for its values
有没有人找到一种方法来获得格式化为具有千位分隔符和固定小数位数的值?我希望图表中的轴值和值格式化。
Has anyone found a way to get values formatted to have thousands separator and a fixed number of decimal places? I would like to have the axis values and values in the chart formatted.
推荐答案
没有数字格式的内置功能在Javascript中。我发现最简单的解决方案是此页面上的addCommas功能。
There is no built-in functionality for number formatting in Javascript. I found the easiest solution to be the addCommas function on this page.
然后,您只需要将 tooltipTemplate
参数行从您的 Chart.defaults.global
修改为像这样:
Then you just have to modify your tooltipTemplate
parameter line from your Chart.defaults.global
to something like this:
tooltipTemplate: "<%= addCommas(value) %>"
Charts.js会处理其余的操作。
Charts.js will take care of the rest.
这是 addCommas
函数:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
这篇关于Chart.js数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!