How do you round a number to two decimal places in C#?

C#DecimalRoundingBankers Rounding

C# Problem Overview


I want to do this using the Math.Round function

C# Solutions


Solution 1 - C#

Here's some examples:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

You might also want to look at bankers rounding / round-to-even with the following overload:

Math.Round(a, 2, MidpointRounding.ToEven);

There's more information on it here.

Solution 2 - C#

Try this:

twoDec = Math.Round(val, 2)

Solution 3 - C#

If you'd like a string

> (1.7289).ToString("#.##")
"1.73"

Or a decimal

> Math.Round((Decimal)x, 2)
1.73m

But remember! Rounding is not distributive, ie. round(x*y) != round(x) * round(y). So don't do any rounding until the very end of a calculation, else you'll lose accuracy.

Solution 4 - C#

Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that string.Format("{0:0.00}", number) is a good approach.

Solution 5 - C#

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

Solution 6 - C#

// convert upto two decimal places

String.Format("{0:0.00}", 140.6767554);        // "140.67"
String.Format("{0:0.00}", 140.1);             // "140.10"
String.Format("{0:0.00}", 140);              // "140.00"

Double d = 140.6767554;
Double dc = Math.Round((Double)d, 2);       //  140.67

decimal d = 140.6767554M;
decimal dc = Math.Round(d, 2);             //  140.67

=========

// just two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

can also combine "0" with "#".

String.Format("{0:0.0#}", 123.4567)       // "123.46"
String.Format("{0:0.0#}", 123.4)          // "123.4"
String.Format("{0:0.0#}", 123.0)          // "123.0"

Solution 7 - C#

This is for rounding to 2 decimal places in C#:

label8.Text = valor_cuota .ToString("N2") ;

In VB.NET:

 Imports System.Math
 round(label8.text,2)

                     

Solution 8 - C#

If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#

Let's see what happens if you want to round to the 3rd decimal:

double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209

result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713

As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.

This applies to negative numbers:

double result = -0.75 * 0.95;  //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713

So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:

double Redondea(double value, int precision, bool roundUp = true)
{
    if ((decimal)value == 0.0m)
        return 0.0;

    double corrector = 1 / Math.Pow(10, precision + 2);

    if ((decimal)value < 0.0m)
    {
        if (roundUp)
            return Math.Round(value, precision, MidpointRounding.ToEven);
        else
            return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
    }
    else
    {
        if (roundUp)
            return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
        else
            return Math.Round(value, precision, MidpointRounding.ToEven);
    }
}

The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.

Solution 9 - C#

I know its an old question but please note for the following differences between Math round and String format round:

decimal d1 = (decimal)1.125;
Math.Round(d1, 2).Dump();	// returns 1.12
d1.ToString("#.##").Dump();	// returns "1.13"

decimal d2 = (decimal)1.1251;
Math.Round(d2, 2).Dump();	// returns 1.13
d2.ToString("#.##").Dump();	// returns "1.13"

Solution 10 - C#

One thing you may want to check is the Rounding Mechanism of Math.Round:

http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

Solution 11 - C#

You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)

You can read more here.

Solution 12 - C#

Had a weird situation where I had a decimal variable, when serializing 55.50 it always sets default value mathematically as 55.5. But whereas, our client system is seriously expecting 55.50 for some reason and they definitely expected decimal. Thats when I had write the below helper, which always converts any decimal value padded to 2 digits with zeros instead of sending a string.

public static class DecimalExtensions
{
    public static decimal WithTwoDecimalPoints(this decimal val)
    {
        return decimal.Parse(val.ToString("0.00"));
    }
}

Usage should be

var sampleDecimalValueV1 = 2.5m;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

decimal sampleDecimalValueV1 = 2;
Console.WriteLine(sampleDecimalValueV1.WithTwoDecimalPoints());

Output:

2.50
2.00

Solution 13 - C#

Math.Floor(123456.646 * 100) / 100 Would return 123456.64

Solution 14 - C#

string a = "10.65678";

decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)

Solution 15 - C#

  public double RoundDown(double number, int decimalPlaces)
        {
            return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLailaView Question on Stackoverflow
Solution 1 - C#Eoin CampbellView Answer on Stackoverflow
Solution 2 - C#John BokerView Answer on Stackoverflow
Solution 3 - C#Colonel PanicView Answer on Stackoverflow
Solution 4 - C#GlenoView Answer on Stackoverflow
Solution 5 - C#ForedeckerView Answer on Stackoverflow
Solution 6 - C#Rae LeeView Answer on Stackoverflow
Solution 7 - C#sadimView Answer on Stackoverflow
Solution 8 - C#fedesanpView Answer on Stackoverflow
Solution 9 - C#Guy PView Answer on Stackoverflow
Solution 10 - C#Michael StumView Answer on Stackoverflow
Solution 11 - C#Kevin W LeeView Answer on Stackoverflow
Solution 12 - C#Riyaz HameedView Answer on Stackoverflow
Solution 13 - C#user3405179View Answer on Stackoverflow
Solution 14 - C#Abhishek JaiswalView Answer on Stackoverflow
Solution 15 - C#RuanView Answer on Stackoverflow