Truncate decimal places with C#

Hi there, I just want to share with you on how to properly truncate decimal places.

Code Snippet
  1. public static class DecimalExtensions
  2. {
  3.     public static decimal TruncateEx(this decimal value, int decimalPlaces)
  4.     {
  5.         if (decimalPlaces < 0)
  6.             throw new ArgumentException(“decimalPlaces must be greater than or equal to 0.”);
  7.  
  8.         if (value == 0) return decimal.Zero;
  9.  
  10.         var modifier = Convert.ToDecimal(0.5 / Math.Pow(10, decimalPlaces));
  11.         return Math.Round(value > 0 ? value – modifier : value + modifier, decimalPlaces, MidpointRounding.AwayFromZero);
  12.     }
  13. }

Example usage :

(9.577M).TruncateEx(2); //9.57

(119.577M).TruncateEx(2); //119.57

Kudos to https://stackoverflow.com/users/94990/nightcoder for the solution. I had added some code to fix bugs regarding MidpointRounding and wrong handling with zero argument.

This extension method is a very neat solution. It will give you immediate access to the truncate method from any decimal in your code.