-1

I've been searching about this question for a few hours but I didn't find my answer so I ask it:

I'm looking for a method or something to round 25,599,999 to 25,000,000 or 25,599,999 to 30,000,000:

 int num1 = 25599999;
 Console.WriteLine(RoundDown(num1, 6 /* This is the places (numbers from end that must be 0) */)) // Should return 25,000,000;

or Round Up:

 int num1 = 25599999;
 Console.WriteLine(RoundUp(num1, 6 /* This is the places (numbers from end that must be 0) */)) // Should return 30,000,000;

Note: I'm not looking for a way to round decimal numbers.

Arad
  • 4,010
  • 5
  • 30
  • 50

4 Answers4

8
int RoundDown(int num, int digitsToRound)
{
    double tmp = num / Math.Pow(10, digitsToRound);

    return (int)(Math.Floor(tmp) * Math.Pow(10, digitsToRound));
}

int RoundUp(int num, int digitsToRound)
{
    double tmp = num / Math.Pow(10, (digitsToRound + 1)) + 1;

    return (int)(Math.Floor(tmp) * Math.Pow(10, (digitsToRound + 1)));
}
Gaurang Dave
  • 3,752
  • 2
  • 13
  • 31
1

Methods for Rounding up and down for expected trailing zero count:

    public static int RoundUp(int number, int trailingZeroes)
    {
        var divider = (int)Math.Pow(10, trailingZeroes);
        return (number / divider + (number % divider > 0 ? 1 : 0)) * divider;
    }

    public static int RoundDown(int number, int trailingZeroes)
    {
        var divider = (int)Math.Pow(10, trailingZeroes);
        return number / divider * divider;
    }

This would however return for:

Console.WriteLine(RoundUp(25599999, 6));

Result will be 26 000 000. If you want it to be rounded to 30 000 000 then you need to call it with 7 trailing zeroes since in your example you are rounding to 7 trailing zeroes:

Console.WriteLine(RoundUp(25599999, 7));
Egres
  • 68
  • 8
0

Take a look at:

Math.Round

Example usage: Rounding a Floating-Point Value

Might be transferable to non-floating point values. Maybe that helps you?

Gereon99
  • 592
  • 6
  • 13
-1

You can try these functions:

public void RoundUp(int n){
    int up = ((n / 1000000) + 1) * 1000000;
    return up;
}

public void RoundDown(int n){
    int down = (n / 1000000) * 1000000;
    return down;
}

This only works with millions number (like 2 000 000, 25 252 325, ...).

Hope it helps!

Adrien G.
  • 371
  • 1
  • 14