Reputation: 15742
I have a flot
graphs with a custom tick formatter function,
if ((val / 1000) >= 1) {
val = String(Math.round(val / 1000)) + 'K';
}
return String(val);
But the issue is it returns same values for some ticks.
Little explanation about code:
val --> any integer value ranging from 1 to infinity
val / 1000
logic is to convert the tick into user friends (readable) format (1K, 2K etc).
But the issue here is I get repeated tick labels when some val
round up to equal values.
It want to know any good way to fix this algorithm to calculate this?
val / 1000
does not mean val is multiple of 1000
it could be any integer value ranging from 1 to infinity.
Eg: For val = 1000 or 1001
it return 1K
on two tick labels.
I know its algorithmic bug .I just wanna to know if there is any way to fix it cleanly
val / 1000
. You can Play round with Math.round()
function.toFixed()
follow Rule 1Upvotes: 0
Views: 216
Reputation: 29126
Here's a solution that uses suffixes for large numbers while keeping the accuracy:
function tick_label(val) {
if (val < 0) return "\u2212" + tick_label(-val);
if (val < 1000) return String(val);
var mag = 1;
var suffix = "";
if (val >= 1000) { mag = 1000; suffix = "k" }
if (val >= 1000000) { mag = 1000000; suffix = "M" }
if (val >= 1000000000) { mag = 1000000000; suffix = "G" }
var div = mag;
while (val % 10 == 0) {
val /= 10;
div /= 10;
}
return String(val / div) + suffix;
}
This code relies on round numbers for ticks, so that the exact number doesn't look strange or overly exact. (A scale of 1.002k, 1.004k, 1.006k looks okay, but a scale of 1.102k, 1.202k, 1.302k does not. I'm not familiar with Flot, but I guess it takes care of that.)
Upvotes: 2