Problem
In C#, I’d like to round a double value to two decimal places. How can I achieve this?
double inputValue = 48.485;
after round up
inputValue = 48.49;
Asked by sanjeev40084
Solution #1
This works:
inputValue = Math.Round(inputValue, 2);
Answered by Alex LE
Solution #2
Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Answered by nandin
Solution #3
ToString with an argument is another simple method. Example:
float d = 54.9700F;
string s = d.ToString("N2");
Console.WriteLine(s);
Result:
54.97
Answered by Diwas
Solution #4
You should use
inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
Math.Round
MidpointRounding
Essentially, the function above will round your input value to 2 (or whatever number you provide) decimal places. When a number is midway between two others, it is rounded to the next number that is away from zero with MidpointRounding.AwayFromZero. You also have the option of rounding to the nearest even number.
Answered by Gage
Solution #5
Use Math.Round
value = Math.Round(48.485, 2);
Answered by recursive
Post is based on https://stackoverflow.com/questions/2357855/round-double-in-two-decimal-places-in-c