1

I need to create a console application as shown in the image below.Console Application

The problem is ,that when I enter the hourly rate with the $, a System.FormatException error occurs. It also says Input string was not in correct format.

Here is the snippet of code that causes the problem

        double rate = 0;
        Console.Write("Enter the hourly rate: ");
        rate = double.Parse(Console.ReadLine());

And here is the whole program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ICA2_Mason_Clarke
{
    class Program
    {

        static void Main(string[] args)
        {
            int hoursWorked = 0;
            Console.Write("Enter the hours worked: ");
            hoursWorked = int.Parse(Console.ReadLine());
            double rate = 0;
            Console.Write("Enter the hourly rate: ");
            rate = double.Parse(Console.ReadLine());
            int taxRate = 0;
            Console.Write("Enter the tax rate as a percent: ");
            taxRate = int.Parse(Console.ReadLine());
            double grossPay = rate * hoursWorked;
            Console.Write("Gross pay : $");
            Console.WriteLine(grossPay);
            double taxesDue = grossPay * taxRate / 100;
            Console.Write("Taxes due : $");
            Console.WriteLine(taxesDue);
            double netPay = grossPay - taxesDue;
            Console.Write("Net pay : $");
            Console.WriteLine(netPay);
            Console.Write("Press any key to continue");
            Console.Read();





        }
    }
}

3 Answers3

3

You could use the double.TryParse overloads to allow the currency Symbol and get the number.

double d;
double.TryParse("$20.00", NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.CurrentCulture, out d);
Console.WriteLine(d);  
Balaji Marimuthu
  • 1,940
  • 13
  • 13
  • Nice answer. Beginning C# v7 you will be able to get rid of the ugly out parameter syntax. No need to declare `d` variable separately. You can write the same code as `if(double.TryParse("$20.00", NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.CurrentCulture, out var d)) { Console.WriteLine(d); }` – RBT Jan 08 '17 at 02:08
  • Thanks @RBT for the explanation. – Balaji Marimuthu Jan 08 '17 at 06:27
1

You could just change the input line:

Console.Write("Enter the hourly rate: $");

the line:

double.Parse(...)

is explained in this link to previous question for parsing currency

Convert any currency string to double

Community
  • 1
  • 1
Wayne
  • 82
  • 4
0

You can use the syntax @"..." to denote a string literal in C#, or you can escape reserved formatting characters using the char \.

For example:

Console.Write(@"Gross pay : $");
zx485
  • 28,498
  • 28
  • 50
  • 59