Round Double To Two Decimal Places

Viewed 90049

Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)

What is the best way to round a double to two decimal places and also have it fixed at 2 decimal places?

Example: 2.346 -> 2.35, 2 -> 2.00

I am hoping to avoid something like this where I have to convert a double to string and then back to a double which seems like a bad way to go about this.

4 Answers
double someValue = 2.346;    
string displayString = someValue.ToString("0.00");

Note that double.ToString (and therefore string.Format()) uses midpoint rounding away from zero, so 0.125 becomes 0.13. This is usually the desired behavior for display. These strings should obviously not be used for round-tripping.

This method is also inappropriate for rounding that is required in mathematical calculations (where MidpointRounding.ToEven is usually the best approach). In that case, Math.Round() should be used.

Related