Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to (1, 2, or 5) x 10^n in Objective-C?

Is there a simple way of rounding a value either down to or to the nearest (1, 2, or 5) x 10^n where n is an integer? As in one of {..., .05 .1, .2, .5, 1, 2, 5, 10, 20, 50, 100...}

Thanks.

like image 809
DenverCoder9 Avatar asked Jun 15 '11 21:06

DenverCoder9


2 Answers

You can take the d=floor(log10(n)) of your number n to get the scale, then divide by 10 to the d to normalize the number to the range of [1.0,10.0). From that point it should be easy to round because there are very limited possibilities. Once you've done that, multiply by 10 to the d to restore the number to the original range.

The following function is in C, I don't know enough about Objective-C to know if this is idiomatic.

double RoundTo125(double value)
{
   double magnitude;
   magnitude = floor(log10(value));
   value /= pow(10.0, magnitude);
   if (value < 1.5)
      value = 1.0;
   else if (value < 3.5)
      value = 2.0;
   else if (value < 7.5)
      value = 5.0;
   else
      value = 10.0;
   value *= pow(10.0, magnitude);
   return value;
}
like image 80
Mark Ransom Avatar answered Oct 20 '22 06:10

Mark Ransom


To round x down to the nearest value of c * 10^n, use

f(c) = c * 10^(floor(log(x/c)))

(assuming x is positive). So to round down to the nearest any of those, just find

max(f(1), f(2), f(5))

To round x up to the nearest value of c * 10^n, use

g(c) = c * 10^(ceiling(log(x/c)))

(again assuming x is positive). So to round up to the nearest of any of those, just find

min(g(1), g(2), g(5))

Now to simply round to the nearest of any of those values, find the nearest rounding down (first paragraph) and the nearest rounding up (second paragraph), and choose whichever is closer to x.

like image 35
BlueRaja - Danny Pflughoeft Avatar answered Oct 20 '22 06:10

BlueRaja - Danny Pflughoeft