Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built in .Net algorithm to round value to the nearest 10 interval

Tags:

c#

math

rounding

How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140.

I can easily do it by hand

return ((int)(number / 10)) * 10; 

But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above.

like image 313
Graviton Avatar asked Nov 08 '08 06:11

Graviton


People also ask

How do you round a value in C#?

In C#, Math. Round() is a Math class method which is used to round a value to the nearest integer or to the particular number of fractional digits. This method has another overload with which, you can specify the number of digits beyond the decimal point in the returned value.

How do you round to the nearest multiple of 10?

To round off a number to the nearest tens, we round off it to the nearest multiple of ten. 78 is situated between 70 and 80. The middle of 70 and 80 is 75. 78 is nearer to 80 and farther from 70.

Does C# round up or down?

4999999" will always round down the the nearest integer. So a 15.5 can never become a 14. Any value that is larger than 14.5 and smaller than 15.5 will round to 15 any value larger than 15.5 and smaller than 16.5 will round to 16.

How do you round to next integer in C#?

The Math. Round() function can be used to round up a double value to the nearest integer value in C#. The Math. Round() function returns a double value that is rounded up to the nearest integer.


1 Answers

There is no built-in function in the class library that will do this. The closest is System.Math.Round() which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly.

public static class ExtensionMethods {     public static int RoundOff (this int i)     {         return ((int)Math.Round(i / 10.0)) * 10;     } }  int roundedNumber = 236.RoundOff(); // returns 240 int roundedNumber2 = 11.RoundOff(); // returns 10 

If you are programming against an older version of the .NET framework, just remove the "this" from the RoundOff function, and call the function like so:

int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240 int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10 
like image 66
Chris Charabaruk Avatar answered Sep 22 '22 17:09

Chris Charabaruk