Set the precision for Decimal numbers in C#

This isn’t exactly what you’re asking, but you could initialize a NumberFormatInfo object within the global scope and use it to format decimals. Here is an example:

using System.Globalization;

NumberFormatInfo setPrecision = new NumberFormatInfo();    
setPrecision.NumberDecimalDigits = 2;    
decimal test = 1.22223;

Console.Write(test.ToString("N", setPrecision)); //Should write 1.23

setPrecision.NumberDecimalDigits = 3;
test = 5m/3m;

Console.Write(test.ToString("N", setPrecision)); //Should write 1.667

MSDN Link: https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo(v=vs.110).aspx

NumberDecimalDigits usage example: https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits(v=vs.110).aspx

Leave a Comment

tech