我使用Highcharts生成折線圖。帶數字格式的高圖(單位)
,我有與numberFormat
一個問題:
var test = 15975000;
numberFormat(test, 0,',','.');
結果是:15.975.000
但我想變換1000
到1k
,100000
到100k
,1000000
到1m
這樣。 我該如何處理這個問題?
我使用Highcharts生成折線圖。帶數字格式的高圖(單位)
,我有與numberFormat
一個問題:
var test = 15975000;
numberFormat(test, 0,',','.');
結果是:15.975.000
但我想變換1000
到1k
,100000
到100k
,1000000
到1m
這樣。 我該如何處理這個問題?
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;
}
參見:How to format numbers similar to Stack Overflow reputation format
NUMBERFORMAT可在Highcharts對象。
Highcharts.numberFormat(test, 0,',','.');
yAxis: {
labels: {
formatter: function() {
return Highcharts.numberFormat(this.value,0);
}
}
},
您需要做的僅僅是:
labels: {
formatter: function() {
return abbrNum(this.value,2); // Need to call the function for each value shown by the chart
}
},
這裏是用來轉換數據的功能要在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;
}
希望這個作品=)
這不能解決單位?! – Philip
你的意思是? –
「但是我想要1000到1k,100000到100k,1000000到1m像這樣,我該如何處理這個問題?」我看不到這解決了這個問題? – Philip