-2

I want to know how I could round to the nearest 100, when a value is truncated. I was using this:

private static int CalculatePaperLevel(int paperLevel)
{
   int roundedLevel = 0;
   roundedLevel = ((int)Math.Round(paperLevel / 10.0) * 10);
   return roundedLevel;
}

but this, is what I want

E.G. 191 -> 100

224 -> 200

140 -> 100

295 -> 200

4 Answers4

9

You could just do roundedLevel = (paperLevel / 100) * 100;

This works because integer arithmetic always truncates results to integers. So

  • (295 / 100) -> 2
  • 2 * 100 -> 200
Daniel
  • 6,595
  • 9
  • 38
  • 70
2

Truncation like this is what happens when you divide two ints in C#. This code does what you want:

private static int CalculatePaperLevel(int paperLevel)
{
   int roundedLevel = paperLevel / 100 * 100;
   return roundedLevel;
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

I believe that the function you want is called Math.Floor.

Ben S.
  • 1,133
  • 7
  • 7
0

Simply use Math.Floor (37D/100)*100

Christian
  • 143
  • 8
  • 2
    The argument `37/100` has type `int`. Why use floor function on an `int`? – Jeppe Stig Nielsen Jun 11 '13 at 22:01
  • @Jeppe It will be handled as decimal since Floor only accepts decimal and double – Christian Jun 11 '13 at 22:04
  • The division will return an `int` since the overload one could describe as `int operator /(int, int)` (defined by C# spec, not necessarily a real .NET method) is clearly the best overload of `/` here. Then the overload of `Floor` to use would be hard to choose. Does this compile? _Edit:_ Ah, you changed it. – Jeppe Stig Nielsen Jun 11 '13 at 22:11