Thursday, August 11, 2022

[FIXED] How do I make my writeline output display the numeric value to the nearest 2 decimal?

Issue

I am just needing to finish up this program for my assignment and I have completed the task that I want it to perform, yet I cannot for the life of me figure out how to make my output display the number value to the second decimal. (For example: 35.50)

My program is meant to take the average of values, and give the numeric average in decimals. It does do that, but the decimal string is way longer than 2 decimal places. I'm hoping to get some advice on how to clean this up, and please give all answers with the explanation. Thank you so much! (The program I am using is visual studios 2017, and I am creating this code within the console app of C#)

static void Main(string[] args)
    {

        decimal counter = 1;
        decimal sum = 0;
        decimal totalLoops = 3;


        while (counter <= totalLoops)
        {
            Console.WriteLine("Please enter test score here:");
            string scoreInput = Console.ReadLine();
            decimal score;
            decimal.TryParse(scoreInput, out score);
            sum += score;
            counter++;

        }

        Console.WriteLine("Your average is {0}", decimal.Round(sum, 2) / decimal.Round(totalLoops, 2));
        Console.ReadKey();

    }

}

Solution

You can use Math.Round

Console.WriteLine("Your average is {0}", Math.Round(decimal.Round(sum, 2) / decimal.Round(totalLoops, 2), 2, MidpointRounding.AwayFromZero));


Answered By - Kei
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.