I put together a function to create "nice numbers" for displaying labels. The function makes use of log10
to normalize odd numbers. Unfortunately, log10
doesn't deal with numbers < 0 but returns NAN.
Now, I have an "ugly" number like -2.36
, how to get the nearest nice number, like -2.3
or -2.0
?
If I convert it to 2.36
in order to put it thru the function and multiply it by -1
afterwards, I'd get -2.4
---> no go, because it is required that nice-number > ugly-number
.
Any ideas?
Links to define nice-numbers etc:
http://wiki.tcl.tk/16640
Algorithm for "nice" grid line intervals on a graph
round to nearest nice number
Here's my code:
function niceNum($range, $round) {
// $exponent: exponent of range
// $fraction: fractional part of range
// $niceFraction: nice, rounded fraction
if ($range==0) return 0;
$exponent = floor(log10($range));
$fraction = $range / pow(10, $exponent);
if ($round) {
if ($fraction < 1.5)
$niceFraction = 1;
elseif ($fraction < 3)
$niceFraction = 2;
elseif ($fraction < 7)
$niceFraction = 5;
else
$niceFraction = 10;
} else {
if ($fraction <= 1)
$niceFraction = 1;
elseif ($fraction <= 2)
$niceFraction = 2;
elseif ($fraction <= 5)
$niceFraction = 5;
else
$niceFraction = 10;
}
return $niceFraction * pow(10, $exponent);
}