SelAromDotNet

A professional .NET developer, educator, creative technologist, electronic musician, and sci-fi/horror nerd.

  • Dev

  • November 14, 2007

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!