This is a very basic article that will explain a few ways of restricting a decimal value to 2 decimal places in C#. Normally, we need to output the decimal values to 2 precision numbers. However, sometimes we also need to restrict the decimal variable itself to store not more than 2 decimal values (for example -12.36). The following are two possible ways to convert a decimal to a string and also restrict it to 2 decimal places.
decimal decimalVar = 123.45M;
string decimalString = "";
decimalString = decimalVar.ToString("#.##");
decimalString = decimalVar.ToString("C");
decimalString = String.Format("{0:C}", decimalvar);
decimalString = decimalVar.ToString("F");
decimalString = String.Format("{0:0.00}", decimalVar);
Now, to convert a decimal back to decimal rounding to 2 decimal places, we can use any one of the following:
decimal decimalVar = 123.45M;
decimalVar = decimal.Round(decimalVar, 2, MidpointRounding.AwayFromZero);
decimalVar = Math.Round(decimalVar, 2);
I hope you mark it in your bookmarks for easy reference. Thanks!