nicenum method
Finds a "nice" number (1, 2, 5, or power-or-ten multiple thereof)
approximately equal to x. Rounds the number if round = true
,
takes ceiling if round = false
.
Implementation
static double nicenum(double x, bool round) {
if (x.abs() < 0.000001) return 0.000001;
double log10x = math.log(x) / math.ln10;
int expv = log10x.floor(); // exponent of x
double f = x / math.pow(10.0, expv); // fractional part of x
double nf; // nice, rounded fraction
if (round) {
if (f < 1.5)
nf = 1.0;
else if (f < 3.0)
nf = 2.0;
else if (f < 7.0)
nf = 5.0;
else
nf = 10.0;
} else {
if (f <= 1.0)
nf = 1.0;
else if (f <= 2.0)
nf = 2.0;
else if (f <= 5.0)
nf = 5.0;
else
nf = 10.0;
}
return nf * math.pow(10.0, expv);
}