28

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.

Community
  • 1
  • 1
Robert
  • 6,086
  • 19
  • 59
  • 84
  • 6
    Adding the two decimal places when they are zero is a visual/representation thing, something `double` itself cares nothing about. So you will for sure need to convert these to strings for display. – Matt Greer Aug 30 '10 at 16:48

4 Answers4

47
double someValue = 2.346;    
String.Format("{0:0.00}", someValue);
Mike
  • 19,267
  • 11
  • 56
  • 72
32

Round the value to the desired precision, and then format it. Always prefer the version of Math.Round containing the mid-point rounding param. This param specify how to handle mid-point values (5) as last digit.

If you don't specify AwayFromZero as the value for param, you'll get the default behaviour, which is ToEven. For example, using ToEven as rounding method, you get:

Math.Round(2.025,2)==2.02 and

Math.Round(2.035,2)==2.04

instead, using MidPoint.AwayFromZero param:

Math.Round(2.025,2,MidpointRounding.AwayFromZero)==2.03 and

Math.Round(2.035,2,MidpointRounding.AwayFromZero)==2.04

So, for a normal rounding, it's best to use this code:

var value=2.346;
var result = Math.Round(value, 2, MidpointRounding.AwayFromZero);
var str=String.Format("{0:0.00}", result );
Rami Alshareef
  • 7,015
  • 12
  • 47
  • 75
Andrea Parodi
  • 5,534
  • 27
  • 46
  • There's no need to round the value. Also, no need to use string.Format(). Instead, you can use `var value = 2.346; var str = value.ToString("0.00");` Whether you use double.ToString() or string.Format(), you'll get midpoint rounding away from zero. So I should rephrase the first sentence: You should only use Math.Round() if you need MidpointRounding.ToEven. – phoog Dec 29 '10 at 20:26
11
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.

phoog
  • 42,068
  • 6
  • 79
  • 117
5

Take a look at Math.Round

AJ.
  • 16,368
  • 20
  • 95
  • 150