How to allow currency symbols in input string C#

912 Views Asked by At

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

There are 3 best solutions below

0
On

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 : $");
2
On

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);  
0
On

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