I\'m writing an application which requires rounding labels to the nearest \'nice\' number. I\'ll put some code below to demonstrate this, but my issue is that I was using a ser
You can use Math.log10 to normalize all values before doing your "nice number" search, something like this:
[Edit] I just realized you are using Java instead of C#, so I modified the code a bit. I don't have a compiler around to test it, but you should get the general idea anyway:
static double getNicerNumber(double val)
{
// get the first larger power of 10
var nice = Math.pow(10, Math.ceiling(Math.log10(val)));
// scale the power to a "nice enough" value
if (val < 0.25 * nice)
nice = 0.25 * nice;
else if (val < 0.5 * nice)
nice = 0.5 * nice;
return nice;
}
// test program:
static void main(string[] args)
{
double[] values =
{
0.1, 0.2, 0.7,
1, 2, 9,
25, 58, 99,
158, 267, 832
};
for (var val : values)
System.out.printf("$%.2f --> $%.2f%n", val, getNicerNumber(val));
}
This will print something like:
0,1 --> 0,1 0,2 --> 0,25 0,7 --> 1 1 --> 1 2 --> 2,5 9 --> 10 25 --> 50 58 --> 100 99 --> 100 158 --> 250 267 --> 500 832 --> 1000