Search code examples
c#mathrounding

How to round a number to the next number due to number of decimal?


Here's my attempted result:

396.6 -> 400
39.66 -> 40
3.96 -> 4
0.396 -> 0.4

How can I do this in C#? Here's my attempt:

public static double CeilToNextSameDecimal(double number)
{
    int decimalPlaces = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2];
    double factor = Math.Pow(10, decimalPlaces);
    return Math.Ceiling(number * factor) / factor;
}

But give to me wrong results (i.e. the same input):

396.6
39.66
3.966
0.3966

Solution

  • Your method of querying the decimal number gets you the number of decimals. However, what we are interested is the number of digits before decimals.

    So what we are looking for is something like the following, which is the cousin of your attempt.

    public static double CeilToNextSameDecimal(double number)
    {
        var digitsBeforeDecimals = Math.Ceiling(Math.Log10(number));
        double factor = Math.Pow(10, digitsBeforeDecimals - 1);
        return Math.Ceiling(number / factor) * factor;
    }
    

    Results in

    120.6 -> 200
    39.66 -> 40
    3.966 -> 4
    0.01 -> 0.01