How to Round Decimal Number in Visual C#

We often make an operation between several number that makes the result of decimal number, some divided numbers can caused a long decimal number behind “.”, and will cause a non desired output! so to avoid this we need to use Math.Round() method, the mentioned can round double or decimal type in accurate way to it’s nearest value.


So let’s make some example!

//Unarranged Output without Math.Round()!
static void Main(string[]args)
{
double b = 11;
for(int a = 1; a<10;a++)
{
 Console.Write(b/a + “\t”);
 a++;
 Console.Write(b/a + “\n”);
}
}

The result Output Will be…


11      5.5
3.66666666666667        2.75
2.2     1.83333333333333
1.57142857142857        1.375
1.22222222222222        1.1
Press any key to continue . . .
Hm,, it doesn’t look so good, so let’s use the Math.Round() Method and make it either decimal max two numbers behind period(.)!
//Arranged Output with Math.Round()!

static void Main(string[]args)
{

double b = 11;

for(int a = 1; a<10;a++)

{

//Math.Round(Decimal Value, Max Decimal Behind Period(.))

 Console.Write(Math.Round( b/a, 2) + “\t”);

 a++;

 Console.Write(Math.Round( b/a, 2) + “\n”);

}

}

And here is the result!

11      5.5
3.67    2.75
2.2     1.83
1.57    1.38
1.22    1.1
Press any key to continue . . .
Cool! now the results are much much better! Notice that the numbers are limited to have maximum two numbers behind period(.),
Okay here are another two modes that can be used in Math.Round(), which is called MidPointRounding Mode
Example!

static void Main(string[] args)

        {
            double a, awayFromZero, toEven;

            a = 123.45;
            awayToZero = Math.Round(a, 1, MidpointRounding.AwayFromZero);
            toEven = Math.Round(a,1,MidpointRounding.ToEven);

            Console.WriteLine(a);
            Console.WriteLine(awayFromZero);
            Console.WriteLine(toEven);

        }
And here is the result…
123.45
123.5
123.4
Press any key to continue . . .
Notice the different between two modes! Yes, the AwayFromZero Mode round the number up by one, and the ToEven mode round to the nearest even value
Thank you for viewing this Visual C# Material, Hope it can help you in future coding~



Leave a Reply