开发者

Scaling Up a Number

How do I scale a numbe开发者_如何学运维r 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


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


import math

exp = math.log10(num)
exp = math.floor(exp)
out = math.ceil(num/10**exp)
out = out * 10**exp


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.


public static int ceilingHighestPlaceValue(int toCeil) 
{
    int placeValue = Math.Pow(10,toCeil.ToString().Length()-1);
    double temp = toCeil / placeValue;
    return= ceil(temp) * placeValue; 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜