PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

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

 August 11, 2022     c#, console-application, decimal, rounding     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing