Rounding Up to 2 Decimal Places in C#

Rounding up to 2 decimal places in C#

Multiply by 100, call ceiling, divide by 100 does what I think you are asking for

public static double RoundUp(double input, int places)
{
double multiplier = Math.Pow(10, Convert.ToDouble(places));
return Math.Ceiling(input * multiplier) / multiplier;
}

Usage would look like:

RoundUp(189.182, 2);

This works by shifting the decimal point right 2 places (so it is to the right of the last 8) then performing the ceiling operation, then shifting the decimal point back to its original position.

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

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.

Round double in two decimal places in C#?

This works:

inputValue = Math.Round(inputValue, 2);

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 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;
}


Related Topics



Leave a reply



Submit