I'm trying to round numbers down to the lowest 100. Basically 199 -> 100, 2021 -> 2000, etc. How can I make this in C# program?
Asked
Active
Viewed 329 times
-2
-
so, what you have tried? – Riad Jan 29 '17 at 06:57
-
1var rounded = number/100*100 – Victor Leontyev Jan 29 '17 at 07:00
-
1Possible duplicate of [Built in .Net algorithm to round value to the nearest 10 interval](http://stackoverflow.com/questions/274439/built-in-net-algorithm-to-round-value-to-the-nearest-10-interval) – Meirion Hughes Jan 29 '17 at 07:42
-
That's not rounding, that is truncation. Math.Truncate() for floating point numbers. Don't forget about negative values. – Hans Passant Jan 29 '17 at 08:22
1 Answers
5
This will do it:
private static int RoundDown(int input)
{
return input / 100 * 100;
}
The reason this works is as follows:
Dividing an integer value by 100 will give the integer portion of the result. This means, if we take the integer 199 and divide by 100, the mathematical result is 1.99 but because we're working with integers, only the 1 is retained. Multiplying this value again by 100 will give you 100 which is the desired result.

Kesty
- 610
- 9
- 19
-
-
-
1
-
1@Kesty - A little explanation as to why this works would be nice. If a novice saw this they would expect `/ 100 * 100` would return the original value. – Enigmativity Jan 29 '17 at 07:25