Round to Nearest 100,1000,10 Pow N

Here is a method which can round a value to nearest 100,1000, or any 10 Pow N.

This method follows the rounding rules –

private static int RoundToNDigits(double value,int digits) 
{
int valueAfterDecimal = Convert.ToInt32(value % Math.Pow(10, digits));
int valueBeforeDecimal = Convert.ToInt32(value) / Convert.ToInt32(Math.Pow(10, digits));
if (valueAfterDecimal < 50)
{
return valueBeforeDecimal * Convert.ToInt32(Math.Pow(10, digits));
}
else if (valueAfterDecimal > 50)
{

return Convert.ToInt32((valueBeforeDecimal + 1) * Math.Pow(10, digits));
}
else
{
if (valueBeforeDecimal % 2 == 0)
return (valueBeforeDecimal + 1) * Convert.ToInt32(Math.Pow(10, digits));
else
return valueBeforeDecimal * Convert.ToInt32(Math.Pow(10, digits));
}
}





 



 



Hope this helps



Cheers

1 Response to "Round to Nearest 100,1000,10 Pow N"

Randy Furco said... April 6, 2009 at 3:27 AM

http://www.getupsyracuse.com

Post a Comment