Search code examples
c#mathfloating-pointdecimaluser-input

C# float and decimal input and math


The user inputs their age, and I have to return that age and then half of the age number in a decimal value, as well as displaying an inputted salary in dollar amounts.

The sample variable I was given included:

    float y;

So here's an example of how I used it in the code I wrote:

    using System;

    public class Profile
    {
        static void Main(string[] args)
        {
            int x;
            float y = 2.0f;
            var result = x / y;

            Console.Write("Please enter your age:");
            x = Covert.ToInt32(Console.ReadLine());

            Console.WriteLine("Your age is {0}, and half your age is {1}."
            , x, result);

            Console.ReadKey();
        }
    }

But if I type a number like "18", it says "Your age is 18, and half of your age is 9." I can't get it to give me something like "9.0" or anything.

I was also shown that my application should state the salary with a decimal and commas (e.g. $250,000.00) but it only shows "$250000." An example of what I used is:

    decimal z;

    Console.Write("Please enter your salary");
    z = Convert.ToDecimal(Console.ReadLine());

    Console.WriteLine("Your salary is {0}.", z);

    Console.ReadKey();

Am I just not supposed to see a decimal in the results?


Solution

  • use the string format options:

    Console.WriteLine("Your age is {0}, and half your age is {1:00.00}."
            , x, result);