Forcing C# to Round Down

I had a business requirement to always round down for a particular value. As you may know, Math.Round does not handle this, nor is there a way to make C# do this out of the box. I found a sample on CodePlex that did the trick.

The specific requirement was to always round down, to four decimal places, so I modified the code slightly. The input was XML, so I treated it as a string first. This was the console app code I ended up with for testing.

class Program
{
static void Main()
{
string v = “1.1231999”;
double d = double.Parse(v);

d *= Math.Pow(10, 4);
d = Math.Floor(d);
d = d * Math.Pow(10, -1 * 4);

Console.WriteLine(d);
Console.ReadLine();
}
}

The explanation is that the code first shifts all digits to be kept to the left of the decimal using the Pow function. Then the remainders are lopped off using the Floor function. Finally, the digits to be kept are shifted back to the right of the decimal using the Pow function with a -1.

In my opinion, this is a lot more elegant than using string manipulation to dynamically truncate remainders beyond 4 decimal places.

For the record, if you want this code to round up instead of down, just change Floor to Ceiling.

Advertisements