How to Round a Number to Two Decimal Places in C#

Rounding a variable to two decimal places C#

Use Math.Round and specify the number of decimal places.

Math.Round(pay,2);

Math.Round Method (Double, Int32)

Rounds a double-precision floating-point value to a specified number
of fractional digits.

Or Math.Round Method (Decimal, Int32)

Rounds a decimal value to a specified number of fractional digits.


How do I display a decimal value to 2 decimal places?


decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m

or

decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m

or

decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m

Rounding decimal number upto two decimal places

It is rounding correctly but you fail to understand that the value is not the format. There is no difference between the two values, 40000 and 40000.00, and you'll have a similar issue with something like 3.1.

Simply use formatting to output whatever number you have to two decimal places, such as with:

Console.WriteLine(String.Format("{0:0.00}", value));

or:

Console.WriteLine(value.ToString("0.00"));

Round double in two decimal places in C#?

This works:

inputValue = Math.Round(inputValue, 2);

Rounding down to 2 decimal places in c#

The Math.Round(...) function has an Enum to tell it what rounding strategy to use. Unfortunately the two defined won't exactly fit your situation.

The two Midpoint Rounding modes are:

  1. AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero. (Aka, round up)
  2. ToEven - When a number is halfway between two others, it is rounded toward the nearest even number. (Will Favor .16 over .17, and .18 over .17)

What you want to use is Floor with some multiplication.

var output = Math.Floor((41.75 * 0.1) * 100) / 100;

The output variable should have 4.17 in it now.

In fact you can also write a function to take a variable length as well:

public decimal RoundDown(decimal i, double decimalPlaces)
{
var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));
return Math.Floor(i * power) / power;
}

Rounding decimals to two decimal places in c#

try:

d = Math.Ceiling(d * 100) / 100;

where d is your decimal.

C# Round Up Two Decimal Places in C#?

Try Ceiling method:

  1. Scale the value up: 6.3619 -> 636.19
  2. Truncate with a help of Math.Ceiling: 636.19 -> 637
  3. Finally, scale the result down: 637 -> 6.37

Code:

 var result = Math.Ceiling(value * 100.0) / 100.0;

Demo:

double[] tests = new double[] {
6.3619,
5.12003,
};

string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,10} -> {Math.Ceiling(test * 100) / 100.0}"));

Console.Write(report);

Outcome:

  6.3619 -> 6.37
5.12003 -> 5.13

Two Decimal places using c#

If you want to round the decimal, look at Math.Round()



Related Topics



Leave a reply



Submit