javascript 带数字格式的高图(单位)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16019645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
highchart with numberformat (unit)
提问by Mi Na Kwon
I'm using Highchartsto generate a line chart.
我正在使用Highcharts生成折线图。
And I'm having a problem with numberFormat
:
我遇到了以下问题numberFormat
:
var test = 15975000;
numberFormat(test, 0,',','.');
the result is: 15.975.000
结果是: 15.975.000
But I want to transform 1000
to 1k
, 100000
to 100k
, 1000000
to 1m
like this.
How can I deal with this problem?
但我想变换1000
到1k
,100000
到100k
,1000000
到1m
这个样子。我该如何处理这个问题?
回答by Sebastian Bochan
numberFormat is available in Highcharts object.
numberFormat 在 Highcharts 对象中可用。
Highcharts.numberFormat(test, 0,',','.');
Example http://jsfiddle.net/DaBYc/1/
示例http://jsfiddle.net/DaBYc/1/
yAxis: {
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value,0);
}
}
},
回答by Jasper de Vries
Write your own formatter(see this example).
formatter: function() {
result = this.value;
if (this.value > 1000000) { result = Math.floor(this.value / 1000000) + "M" }
else if (this.value > 1000) { result = Math.floor(this.value / 1000) + "k" }
return result;
}
See also: How to format numbers similar to Stack Overflow reputation format
回答by Felipe Campanhol
You just need to do that:
你只需要这样做:
labels: {
formatter: function() {
return abbrNum(this.value,2); // Need to call the function for each value shown by the chart
}
},
Here is the Function used to transform the data to be inserted on javascript:
这是用于转换要插入到 javascript 上的数据的函数:
function abbrNum(number, decPlaces) {
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = Math.pow(10,decPlaces);
// Enumerate number abbreviations
var abbrev = [ "k", "m", "b", "t" ];
// Go through the array backwards, so we do the largest first
for (var i=abbrev.length-1; i>=0; i--) {
// Convert array index to "1000", "1000000", etc
var size = Math.pow(10,(i+1)*3);
// If the number is bigger or equal do the abbreviation
if(size <= number) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round(number*decPlaces/size)/decPlaces;
// Handle special case where we round up to the next abbreviation
if((number == 1000) && (i < abbrev.length - 1)) {
number = 1;
i++;
}
// Add the letter for the abbreviation
number += abbrev[i];
// We are done... stop
break;
}
}
return number;
}
Hope this works =)
希望这有效 =)