Rounding to the Nearest Ten

I'm not sure if the Microsoft .NET Framework has support for rounding to the nearest ten, hundreds, thousands, etc, so I built a quick snippet of code to accomplish this.

The basic algorithm is to mod the value by 10 (can be modified to handle 100, 1000, etc), then if less than the median (in this case 5), subtract that from the original value. If the mod is greater than or equal to the median, we round up by adding the DIFFERENCE between the remainder and the rounding base (10 in this case).

// get remainder 
int rem = numToRound % 10; 
if (rem < 5) 
	// round down, subtract remainder 
   rounded -= rem; 
else 
	//round up, add diff b/t 10 and remainder 
	rounded += (10 - rem); 

return rounded; 

If there is a built in function, please feel free to link it to me in the comments section. If not, I might encapsulate this into my own SelArom.Math class and allow users to specify the base. Hope this was helpful to someone!

Enjoyed this post and/or found it useful?
Tagged with:
SelArom Dot Net Profile Image
SelAromDotNet

Josh loves all things Microsoft and Windows, and develops solutions for Web, Desktop and Mobile using the .NET Framework, Azure, UWP and everything else in the Microsoft Stack.

His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom.



Scroll to top