Hi there, I just want to share with you on how to properly truncate decimal places.
Code Snippet
- public static class DecimalExtensions
- {
- public static decimal TruncateEx(this decimal value, int decimalPlaces)
- {
- if (decimalPlaces < 0)
- throw new ArgumentException(“decimalPlaces must be greater than or equal to 0.”);
- if (value == 0) return decimal.Zero;
- var modifier = Convert.ToDecimal(0.5 / Math.Pow(10, decimalPlaces));
- return Math.Round(value > 0 ? value – modifier : value + modifier, decimalPlaces, MidpointRounding.AwayFromZero);
- }
- }
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.