C# float and decimal input and math - c#

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.

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# Compound Interest Calculator (beginner)

C# beginner, trying to create a program where a user enters an amount, years, and rate and then calculates the total amount. The rate will be divided by 100 to get the decimal value and the years will be multiplied by 12 to get the monthly rate.
Here is the code:
class Program
{
static void Main(string[] args)
{
CompoundClass program = new CompoundClass();
Console.Write("Please enter the initial balance for your account: ");
double balance = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the annual interest rate: ");
double interestRate = Convert.ToDouble(Console.ReadLine());
program.Rate(interestRate);
Console.Write("How many years will you acrue interest? ");
double anualAmount = Convert.ToDouble(Console.ReadLine());
program.Years(anualAmount);
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
Console.ReadLine();
}
}
class CompoundClass
{
public double rate;
public double yearlyRate;
public double balance;
public void Rate(double interestRate)
{
if (interestRate > 0)
{
rate = interestRate / 100;
}
}
public void Years(double anualAmount)
{
if (anualAmount > 0)
{
yearlyRate = anualAmount * 12;
}
}
public void addMethod(double totalAmount)
{
for (int i = 1; i < yearlyRate + 1; i++)
{
totalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
}
}
I keep getting the error:
CS0103The name 'totalAmount' does not exist in the current context.
I don't know if any information is being pulled correctly and stored/calculated.
You are having that error because the 'totalAmount' variable can only be accessed inside CompoundClass. This is because it is created with a default access modifier private.
You created an object for CompoundClass
CompoundClass program = new CompoundClass();
You have accessed the methods using the object. Regarding your question for annualAmount or interestRate, you didn't access the variables from CompoundClass, you have just passed them from Program class. However you can still access rate, yearlyRate, and balance through the object like program.rate and so on. This is because you have declared them as public.
public double rate;
public double yearlyRate;
public double balance;
If you want to access totalAmount as well, please declare that as public.
program.addMethod(balance);
Console.WriteLine($"Your balance after {anualAmount} years is {program.totalAmount:C}\n");
You are trying to print out (from program) the value of a variable that you have not declared (totalAmount from within program).
Since it is looking like you want to calculate totalAmount you want to change your addMethod to return the calculated amount instead of accepting totalAmount as a parameter.
For example in program do
double totalAmount = addMethod();
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
And implement addMethod to return the value:
public void addMethod()
{
double calculatedTotalAmount = 0;
for (int i = 1; i < yearlyRate + 1; i++)
{
calculatedTotalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
return calculatedTotalAmount;
}
Effectively, you are assigning the value calculated within the scope of the method to totalAmount, which is declated in the outer scope.

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

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

How to parse user input to int in console application

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;

How do I format cents and dollars in C#? How do I convert one to the other?

If I have something written as 25 cents in either C# or Java, how would I convert that to read $.25?
You should probably use the Decimal datatype, and then instead of trying to convert cents to dollars, use one standard notation:
Decimal amount = .25M;
String.Format("Amount: {0:C}", amount);
The output is: Amount: $0.25;
class Money
{
public int Dollar {get; set;}
public int Cent { get; set;}
public Money(int cents)
{
this.Dollar = Math.Floor(cents/100);
this.Cent = cents%100;
}
}
and u can use it like so
int cents = Convert.ToInt32(Console.Readline("Please enter cents to convert:"))
Money money = new Money(cents);
Console.Writeline("$" + money.Dollar + "." + money.Cent);
I think this is Best Answer I write with Array
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please input your cent or dollar");
int coins = int.Parse(Console.ReadLine());
int[] dollars = new int[2];
dollars[0] = coins / 100;
dollars[1] = coins % 100;
Console.WriteLine("{0} dollar and {1} coins", dollars[0], dollars[1]);
Console.ReadLine();
}

Categories