views:

72

answers:

4

How do I scale a number up to the nearest ten, hundred, thousand, etc...

Ex.

num = 11 round up to 20
num = 15 round up to 20
num = 115 round up to 200
num = 4334 round up to 5000
+2  A: 

I guess this formula might work? Unless you have more examples to show.

power = floor(log10(n))
result = (floor(n/(10^power)) + 1) * 10^power
CookieOfFortune
This wouldn't work, if you did 15 it would return for result ((15/10) + 1) * 10 which is 25
Rafe Kettler
@Rafe Kettler it works if you do integer division or do Math.Floor(15/10)
Arizona1911
yeah, I did mean integer division. It's been updated to be more explicit.
CookieOfFortune
+1  A: 

Convert the number to a decimal (i.e. 11 goes to 1.1, 115 goes to 1.15), then take the ceiling of the number, then multiply it back. Example:

public static int roundByScale(int toRound) {
    int scale = (int)Math.pow(10.0, Math.floor(Math.log10(toRound)));
    double dec = toRound / scale;
    int roundDec = (int)Math.ceil(dec);
    return roundDec * scale;
}

In this case, if you input 15, it will be divided by 10 to become 1.5, then rounded up to 2, then the method will return 2 * 10 which is 20.

Rafe Kettler
Doesn't work for 10**n.
joel3000
it does now....
Rafe Kettler
+1  A: 
import math

exp = math.log10(num)
exp = math.floor(exp)
out = math.ceil(num/10**exp)
out = out * 10**exp
joel3000
A: 
public static int ceilingHighestPlaceValue(int toCeil) 
{
    int placeValue = Math.Pow(10,toCeil.ToString().Length()-1);
    double temp = toCeil / placeValue;
    return= ceil(temp) * placeValue; 
}
Jack