How to parse user input to int in console application - c#

I want to create a C# application that inputs one salesperson's item sold for the last week and calculates and displays that salesperson's earnings. The sales person receives $200 per week plus 9% of their gross sales for that week. Having been supplied a list of items sold by each salesperson and their values, how do I convert the user input to int? Everything else works fine.
double value1, value2, value3, value4;
value1 = 239.99;
value2 = 129.75;
value3 = 99.95;
value4 = 350.89;
Console.Write("Enter number sold of product #1: ");
int item1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #2: ");
int item2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #3: ");
int item3 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #4: ");
int item4 = Convert.ToInt32(Console.ReadLine());
double sales1, sales2, sales3, sales4, totalSales;
sales1 = item1 * value1;
sales2 = item2 * value2;
sales3 = item3 * value3;
sales4 = item4 * value4;
totalSales = sales1 + sales2 + sales3 + sales4;
double commission;
int weeklyPay = 200;
commission = (9/100) * totalSales;
double salary;
salary = commission + weeklyPay;
Console.Write("Earnings this week: " + salary);
Console.ReadLine();

Although your approach seems correct at first sight, you should cast strings into simple datatypes in a non-vexing style.
Check this (quite verbose) code:
string userInput = Console.ReadLine();
int parsedValue;
if(!Int32.TryParse(userInput, out parsedValue))
{
// Decide what to do here, parsing failed!
}
else
{
// String format from user was valid and parsed value is in parsedValue variable.
}
If your are interested in a more detailed argument of why this is better coding, check Eric Lippert article about Vexing Exceptions.

Earnings this week will always return 200. This is not because the user input is not being read (see jih's answer for a more robust method of parsing a string to an int) but because of a bug:
commission = (9/100) * totalSales;
The problem is that you are doing integer division.
Try
commission = 0.09 * totalSales;
or
commission = 9.0/100.0 * totalSales;
The parentheses around 9/100 are redundant but are ok if they improve readability.

try this
commission = ((double)9/100) * totalSales;

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

Convert money input into coins

ive just started some classes on c# and have been given an assignment with the following rules:
Prompt the user to enter an amount of dollars and cents. For example 1.18
- Display the number of quarters, dimes, nickels, and pennies to make that amount
Example If they entered 2.16 it should say:
8 quarters, 1 dimes, 1 nickels, 1 pennies
the problem that i run into is that this only seems to work if they type the money value as a whole. so if they wanted to type $1.18 they would type 118 and it would work just fine, but as soon as they type 1.18 it crashes. another example would be if they were to type 765 for $7.65 it would work fine, however if they type it correctly as 7.65 it would fail. sorry for the lame question, im super new, thanks for the help!
int totalCash;
Console.WriteLine("input money");
string moneyString = Console.ReadLine();
totalCash = int.Parse(moneyString);
int quarter = totalCash / 25;
totalCash %= 25;
int dime = totalCash / 10;
totalCash %= 10;
int nickel = totalCash / 5;
totalCash %= 5;
int penny = totalCash / 1;
totalCash %= 1;
Console.WriteLine("{0} quarters, {1} dimes, {2} nickels, {3} pennies", quarter, dime, nickel, penny);
```
There are lots of ways get the result but this the best approach I ever tried :
public static string ConvertMoneyIntoCoins(double money)
{
int cents = (int)(Math.Round(money, 2) * 100);
var coins = new[] {
new { Name = "Quarters", Value = 25 }, new { Name = "Dimes", Value = 10 },
new { Name = "Nickels", Value = 5 }, new { Name = "Pennies", Value = 1 }
};
var changes = coins.Select(coin => new { Amt = Math.DivRem(cents, coin.Value, out cents), Coin = coin }).Where(x => x.Amt != 0).ToList();
var strBld = new StringBuilder();
foreach (var change in changes)
{
strBld.Append(change.Amt + " " + change.Coin.Name + ", ");
}
return strBld.ToString();
}
It's working when you enter whole number should be the clue you pay attention to. If you assume the whole number is dollars, you can not mod by a whole number. All of your divisors are a factor of 100 too big. When you do that, you'll notice that you have the wrong data type as well. Note that i disagree with using tryparse when debugging as it eats errors. You should be running it in debug mode and then you would get an actual stack trace and a line it crashes at.

Payroll Array Issues (unsure why calculations do not begin) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
public struct pay
{
public string name;
public int rate;
public int hours;
public int gross;
public int wtd;
public int ssd;
public int md;
public int net;
}
static void Main(string[] args)
{
pay[] myPay = new pay[3];
for (int i = 0; i<= 2; i++)
{
Console.WriteLine("Enter name: ");
myPay[i].name = Console.ReadLine();
Console.WriteLine("Enter pay rate: ");
myPay[i].rate = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter hours worked: ");
myPay[i].hours = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("Name\tRate\tHours\tGross\t W/T\tSS\tMed\tNet");
for (int i = 0; i<=2; i++)
{
int gross = (myPay[i].rate * myPay[i].hours);
int wtd = (myPay[i].gross * (1/20));
int ssd = (myPay[i].gross * (3 / 100));
int md = (myPay[i].gross * (1 / 100));
int net = (myPay[i].gross - (md + ssd + wtd));
Console.WriteLine(myPay[i].name + "\t" + myPay[i].rate + "\t" + myPay[i].hours + "\t" + myPay[i].gross + "\t" + myPay[i].wtd + "\t" + myPay[i].ssd + "\t" + myPay[i].md + "\t" + myPay[i].net);
}
Console.ReadLine();
}
}
The code is intended to take the name, rate, and hours worked of an employee to find gross pay. Then, costs will be taken from gross pay (each indicated with WTD, SD, and MD) to find the net income for the employee.
For whatever reason, the calculations for gross pay never begin, and therefore the following calculations do not register either. Any help would be greatly appreciated!
If you need a decimal value, you cant store it in an int
int (C# Reference)
If you are going to be calculating money you need to use a decimal
decimal (C# Reference)
Struct
public struct pay
{
public string name;
public int rate;
public int hours;
public decimal gross;
public decimal wtd;
public decimal ssd;
public decimal md;
public decimal net;
public void Calculate()
{
gross = (rate * hours);
wtd = (gross * (1 / (decimal)20));
ssd = (gross * (3 / (decimal)100));
md = (gross * (1 / (decimal)100));
net = (gross - (md + ssd + wtd));
}
}
Usage
static void Main(string[] args)
{
pay[] myPay = new pay[3];
for (int i = 0; i <= 2; i++)
{
Console.WriteLine("Enter name: ");
myPay[i].name = Console.ReadLine();
Console.WriteLine("Enter pay rate: ");
myPay[i].rate = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter hours worked: ");
myPay[i].hours = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("Name\tRate\tHours\tGross\t W/T\tSS\tMed\tNet");
for (int i = 0; i <= 2; i++)
{
myPay[i].Calculate();
Console.WriteLine($"{myPay[i] .name}\t{myPay[i] .rate}\t{myPay[i] .hours}\t{myPay[i] .gross}\t{myPay[i] .wtd}\t{myPay[i] .ssd}\t{myPay[i] .md}\t{myPay[i] .net}");
}
Console.ReadLine();
}
Output
Enter name:
dfg
Enter pay rate:
4
Enter hours worked:
5
Enter name:
dh
Enter pay rate:
56
Enter hours worked:
7
Enter name:
fjh
Enter pay rate:
56
Enter hours worked:
4
Name Rate Hours Gross W/T SS Med Net
dfg 4 5 20 1.00 0.60 0.20 18.20
dh 56 7 392 19.60 11.76 3.92 356.72
fjh 56 4 224 11.20 6.72 2.24 203.84
Disclaimer, i just fixed up the glaring problems, however i am not liable for anyone you maim or otherwise injure with this code
I think your problem is using int as a variable, you should use decimal variable when calculating salaries or anything that involves currency to have exact result.

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