How to allow currency symbols in input string C# [duplicate] - c#

This question already has answers here:
Find and extract a number from a string
(32 answers)
Convert any currency string to double
(3 answers)
Closed 6 years ago.
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();
}
}
}

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

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

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

Related

I am not able to convert final answer into decimal form

I am not able to bring my final output in decimal terms
When i tried to convert double to decimal it gives error
using System;
namespace Recurring_Deposit_Calc
{
class Program
{
private double _amount, _month,_a;
private double _b,_simpleintrest,_matureAmount,_x;
public void Calulate() {
Console.WriteLine("Intrest Rate :6.8%");
Console.WriteLine("Enter amount you deposit per month:");
_amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter months:");
_month = Convert.ToInt32(Console.ReadLine());
//Calculting Simple Intrest
_simpleintrest = _amount * _month*_a/ 2 * 12*_b;
_a = _month + 1;
_b = 7.65/100;
//Calculating Maturity Amount
_x = _amount * _month;
_matureAmount = _x + _simpleintrest;
Console.WriteLine("Amount is :{0}",_matureAmount);
}
}
Code link
Output
If you want convert to decimal, you can use the Convert.ToDecimal method.
Console.WriteLine("Amount is :{0}",_matureAmount.ToString("0.00"));
If you want upto 1 decimal place, use .ToString("0.0").
I got the output as expected
New problem how to reduce the place value of final answer
private double p, r = 6.8, i, totalDeposit, maturityAmount;
private int n;
public static void Main(string[] args){
Console.WriteLine("Interest Rate :6.8%");
Console.WriteLine("Please enter per month deposit amount:");
p = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter months:");
n = Convert.ToInt32(Console.ReadLine());
//recurring deposit simple interest formula
//i=p*(n(n+1)/2*12)*r/100
i = p * (n * (n + 1) * r / 2400);
totalDeposit = p * n;
maturityAmount = totalDeposit + i;
Console.WriteLine("Amount of maturity = " +
"Totoal money deposited+Interest:{0}+{1}={2}", totalDeposit, i, maturityAmount);
}
Output
******Recurring Deposit Calculator******
Interest Rate :6.8%
Please enter per month deposit amount:
4567
Enter months:
7
Amount of maturity = Totoal money
deposited+Interest:31969+724.6306666666667=32693.630666666668

C# showing wrong output, but other output based on it is correct

I'm having a problem with the last line for "deduction".
it's a program to calculate an employee's net pay. every output is coming up as the teacher wants except for the deductions. when ran it's showing "292.22" instead of "368.72" with input being: hours = 48.55, rate = 25.50, and dependents = 3.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program5
{
class NetPay
{
static double hours, rate, dependents;
const double TAXRATE = .23;
const double DEPENDENTS = 25.50;
static void Main(string[] args)
{
GetInput();
Calculations();
}
static void GetInput()
{
Console.Write("Enter hours worked: ");
hours = double.Parse(Console.ReadLine());
Console.Write("Enter hourly rate: ");
rate = double.Parse(Console.ReadLine());
Console.Write("Enter number of dependents: ");
dependents = double.Parse(Console.ReadLine());
}
static void Calculations()
{
double gross, netPay, deduction;
Console.WriteLine("\nHourse Worked:\t\t\t\t\t {0:c}", hours);
Console.WriteLine("Hourly Rate:\t\t\t\t\t {0:c}", rate);
Console.WriteLine("Dependents:\t\t\t\t\t\t{0}", dependents);
if (hours > 40)
gross = Math.Round((((hours - 40) * 1.5 ) * rate) + (40 * rate), 2);
else
gross = Math.Round(hours * rate, 2);
Console.WriteLine("Gross Pay:\t\t\t\t\t{0:c}", gross);
dependents = Math.Round(dependents * DEPENDENTS, 2);
gross = gross - dependents;
deduction = Math.Round(gross * TAXRATE, 2);
Console.WriteLine("Deductions:\t\t\t\t\t{0:c}", deduction);
Console.WriteLine("\t\t\t\t\t\t---------");
netPay = gross - deduction;
Console.WriteLine("Net Pay:\t\t\t\t\t{0:c}", netPay);
}
}
}

C# fahrenheit to celsius

public static void Main()
{
WriteLine("Farenheit Here>>");
int F = Int32.Parse(ReadLine());
Double FtoC = (5.0 / 9.0) * (F - 32);
WriteLine("the celsius is {0} ", FtoC);
}
The input works for whole numbers but I also want it to work for Decimal numbers. Ex. If I were to type in 10 it will give me an answer, but if I were to type in 10.5 it will stop working. I am indeed new to C#.
you need to use the number parser you want, currently you are using int
Int32.Parse(ReadLine());
You can use double, or decimal (I'd suggest using decimal over double)
decimal F = Decimal.Parse(ReadLine());
then change to
decimal FtoC = (5.0M / 9.0M) * (F - 32M);
WriteLine("the celsius is {0} ", FtoC)
(the M is used to define decimal literals)
int does not store decimal number. Use double or decimal
public static void Main()
{
WriteLine("Farenheit Here>>");
double F = double.Parse(ReadLine());
Double FtoC = (5.0 / 9.0) * (F - 32);
WriteLine("the celsius is {0} ", FtoC);
}
Well, Int32 is specifically for handling integers. If you want to handle Decimal values, they have their own Parse method so I'd be looking at something like:
public static void Main() {
Console.Write("Farenheit Here>> ");
Decimal F = Decimal.Parse(Console.ReadLine());
Decimal FtoC = (5.0M / 9.0M) * (F - 32M);
Console.WriteLine("The celsius is {0} ", FtoC);
}
And note the use of the M suffix. If you want to use Decimal types, you're probably better off committing fully to them, rather than reverting to the double type with all its foibles.

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?
use the string format options:
Console.WriteLine("Your age is {0}, and half your age is {1:00.00}."
, x, result);
You need to perform your math AFTER you get input from the user.

c# using operators with calculations (net pay) (gross pay)

I don't understand if the calculation for netPay = grossPay - (fedtax withholding + social security tax withholding). Are my calculations correct within the program? Dealing with such in editedTax?? If someone could help I'd appreciate it.
More info: When I display netPay within an output, I receive a runtime error, where I couldn't convert the negative to currency with {0:c2}.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
string empName;
string userInput;
double netPay;
double editedTax1;
double grossPay;
double editedTax2;
double hrsWorked;
double ovtWorked;
double payRate;
const double FED_TAX = .28;
const double SS_TAX = 7.65;
// step 1
Console.WriteLine(" WEEKLY PAYROLL INFORMATION");
// step 2
Console.WriteLine(" --------------------------");
// step 3
Console.Write("\n Please enter the employer's name: ");
empName = Console.ReadLine();
//step 4
Console.Write("\n Please enter the number of hours worked this week: ");
userInput = Console.ReadLine();
hrsWorked = Convert.ToDouble(userInput);
// step 5
Console.Write("\n Please enter the number of OVERTIME HOURS worked this week: ");
userInput = Console.ReadLine();
ovtWorked = Convert.ToInt32(userInput);
// step 6
Console.Write("\n Please enter employee's HOURLY PAY RATE: ");
userInput = Console.ReadLine();
payRate = Convert.ToDouble(userInput);
// step 7
grossPay = (hrsWorked * payRate + ovtWorked * 1.5 * payRate);
// step 8
editedTax1 = FED_TAX * grossPay;
// step 9
editedTax2 = SS_TAX * grossPay;
// step 10
netPay = editedTax1 + editedTax2 - grossPay;
// step 11
Console.WriteLine("\n\n The weekly payroll information summary for: " + empName);
Console.WriteLine("\n Gross pay: {0:C2} ", grossPay);
// step 12
Console.WriteLine(" Federal income taxes witheld: {0:C2} ", editedTax1);
Console.WriteLine(" Social Security taxes witheld: {0:C2} ", editedTax2);
Console.WriteLine(" Net Pay: {0:C2}", netPay);
}
}
}
netPay is assigned the opposite value in the code as compared to your description below.
I don't see any syntax errors or anything.
What is the problem you're having? What are some of the things you've tried?
The reason you're getting a negative number in the calculation is because your SS_TAX is 7.65. I think the number you want is 0.0765.
I'm not sure exactly what you're asking for, but simple substitution in the assignment statements yields the following formulas:
Since
editedTax1 = FED_TAX * grossPay;
editedTax2 = SS_TAX * grossPay;
netPay = editedTax1 + editedTax2 - grossPay;
then
netPay = FED_TAX * grossPay + SS_TAX * grossPay - grossPay;
meaning
netPay = grossPay * (FED_TAX + SS_TAX - 1);
so something seems a little off here...
Are you sure you don't want
netPay = grossPay - (editedTax1 + editedTax2);
instead of
netPay = editedTax1 + editedTax2 - grossPay;
This seems to match what you're looking for as
netPay = grossPay - (FED_TAX * grossPay + SS_TAX * grossPay);
or
netPay = grossPay * (1 - (FED_TAX + SS_TAX));
...unless I'm missing something, of course.
Edit: I was missing something. Your tax constants are a percent, but you're not dividing by 100 when you do calculations with them. You have two options:
Divide by 100 when you use the values in a calculation, like:
editedTax1 = (FED_TAX / 100) * grossPay;
Store the constants as the decimal representation, not a percent, like:
const double FED_TAX = .0028;
I have tested this code on my machine and it works correctly:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
const double FEDERAL_TAX_RATE= 0.28;
const double SOCIAL_SECURITY_RATE = 0.0765; // I am assuming the 7.65 was supposed to be 7.65%... therefore it should be 0.0765
Console.WriteLine(" WEEKLY PAYROLL INFORMATION");
Console.WriteLine(" --------------------------");
Console.Write("\n Please enter the employer's name: ");
string empName = Console.ReadLine();
Console.Write("\n Please enter the number of hours worked this week: ");
double hrsWorked = Convert.ToDouble(Console.ReadLine());
Console.Write("\n Please enter the number of OVERTIME HOURS worked this week: ");
double ovtWorked = Convert.ToInt32(Console.ReadLine());
Console.Write("\n Please enter employee's HOURLY PAY RATE: ");
double payRate = Convert.ToDouble(Console.ReadLine());
double grossPay = CalculateGrossPay(hrsWorked, payRate, ovtWorked);
double federalTaxWithheld = CalculateTax(grossPay, FEDERAL_TAX_RATE);
double socialSecurityWithheld = CalculateTax(grossPay, SOCIAL_SECURITY_RATE);
double netPay = CalculateNetPay(grossPay, federalTaxWithheld + socialSecurityWithheld);
Console.WriteLine("\n\n The weekly payroll information summary for: " + empName);
Console.WriteLine("\n Gross pay: {0:C2} ", grossPay);
Console.WriteLine(" Federal income taxes witheld: {0:C2} ", federalTaxWithheld);
Console.WriteLine(" Social Security taxes witheld: {0:C2} ", socialSecurityWithheld);
Console.WriteLine(" Net Pay: {0:C2}", netPay);
Console.ReadLine(); // You don't need this line if your running from the command line to begin with
}
static double CalculateGrossPay(double HoursWorked, double PayRate, double OvertimeHoursWorked)
{
return PayRate * (HoursWorked + 1.5 * OvertimeHoursWorked);
}
static double CalculateTax(double GrossPay, double TaxRate)
{
return GrossPay * TaxRate;
}
static double CalculateNetPay(double GrossPay, double TaxAmount)
{
return GrossPay - TaxAmount;
}
}
}
Since it looks as though this is your first programming course, I'll offer you some pointers that they probably will not emphasize in your class:
Use descriptive variable names. If you notice yourself putting a number after your variable name, it can probably done a different and more readable way!
Utilize functions, they bundle common tasks in one section of code and increase readability significantly.
You may want to add some exception handling or validation to this code. For example, what if you accidentally passed -1 into OverTimeHours?
I understand this might not matter at this point in your programming journey, but it's always good to start off using coding techniques that make your code more readable and less confusing, especially for people who may have to maintain it in the future.

Categories