Round double in two decimal places in C#?

ID : 10151

viewed : 69

Tags : c#doubleroundingc#

Top 5 Answer for Round double in two decimal places in C#?

vote vote

97

This works:

inputValue = Math.Round(inputValue, 2); 
vote vote

89

Math.Round(inputValue, 2, MidpointRounding.AwayFromZero) 
vote vote

70

Another easy way is to use ToString with a parameter. Example:

float d = 54.9700F;     string s = d.ToString("N2"); Console.WriteLine(s); 

Result:

54.97 
vote vote

70

You should use

inputvalue=Math.Round(inputValue, 2, MidpointRounding.AwayFromZero) 

Math.Round

Math.Round rounds a double-precision floating-point value to a specified number of fractional digits.

MidpointRounding

Specifies how mathematical rounding methods should process a number that is midway between two numbers.

Basically the function above will take your inputvalue and round it to 2 (or whichever number you specify) decimal places. With MidpointRounding.AwayFromZero when a number is halfway between two others, it is rounded toward the nearest number that is away from zero. There is also another option you can use that rounds towards the nearest even number.

vote vote

56

Use Math.Round

value = Math.Round(48.485, 2); 

Top 3 video Explaining Round double in two decimal places in C#?

Related QUESTION?