
How To Round a decimal value to 2 decimal places in C#
Friends,
This is a very basic post that will explain 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 ex -12.36). Below are the ways you can use 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);
Hope you mark it in your bookmarks for easy reference. Thanks!