I am not able to convert final answer into decimal form - c#

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

Related

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 multiply two numbers and get the SUM every two numbers is multiply?

Good day everyone! Hope this work. I have to 2 textboxes and I convert it to integer the num1 and num2. I want to display it into textSubtotal. For example 10 * 10 = 100. I want to multiply another 2 numbers the value is 20 * 20 = 400. Add it to 100 so the answer will be 100 + 400 = 500. But the problem is I received an error in this line textSubtotal.Text = Convert.ToString(float.Parse(textSubtotal.Text) + sum) Input string was not in a correct format. Can somebody help me regarding to my problem?
private void buttonOrder_Click(object sender, EventArgs e)
{
float num1, num2, product = 0, sum = 0;
num1 = float.Parse(textPrice.Text);
num2 = float.Parse(textQuantity.Text);
product = num1 * num2; sum = sum + product;
textSubtotal.Text = Convert.ToString(float.Parse(textSubtotal.Text) + sum);
}
You don't need to struggle with Textbox string conversions to do that. Use a private field:
private float subTotal = 0; // this would be a field in your class
private void buttonOrder_Click(object sender, EventArgs e)
{
float num1 = float.Parse(textPrice.Text);
float num2 = float.Parse(textQuantity.Text);
subTotal += num1 * num2;
textSubtotal.Text = subTotal;
}
You should check that the two fields contain actual numeric values (see float.TryParse()). Also, consider using decimal (not float) for this kind of calculations.

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

Having incorrect solutions when program executes,

I've been working on a two class BMI Calculator for my class. I finally have managed to debug on get the program to execute. However I noticed that it wont let me enter height or weight as a decimal.
Example
putting 6.4 for height causes it to crash
Putting 6 height and 220 weight always seems to declare underweight and show incorrect bmi reading
example:
Height 6
Weight 220
BMI: score $0.09
It's calculating the BMI wrong. Looking at the code I can't seem to identify why its calculating this wrong.
-Edit- Managed to get it to take decimals! (Thank you everyone!) However it still seems to be messing up calculating the BMI
-Edit- Code Works!
(Code Part 1) Updated Mk2
using System;
namespace Calculator
{
public class BMICalc
{
private const
decimal REQ = 703;
private decimal weightPerson;
private decimal heightPerson;
public BMICalc()
{
}
public BMICalc(decimal weiP, decimal heiP)
{
this.weightPerson = weiP;
this.heightPerson = heiP;
}
public decimal SetBmi()
{
decimal bmi;
bmi = Convert.ToDecimal((this.weightPerson * 0.45m) / ((this.heightPerson * 12 * 0.025m) * (this.heightPerson * 12 * 0.025m)));
if (bmi < 18.5m)
{
Console.WriteLine("UnderWeight");
Console.ReadLine();
}
if (bmi > 18.5m && bmi < 25.0m)
{
Console.WriteLine("Normal");
Console.ReadLine();
}
if (bmi > 25.0m && bmi < 29.9m)
{
Console.WriteLine("OverWeight");
Console.ReadLine();
}
if (bmi > 29.9m && bmi < 40.0m)
{
Console.WriteLine("Obese");
Console.ReadLine();
}
return bmi;
}
public override string ToString()
{
return "\tCalculator" +
"\n\n Weight:" + this.weightPerson +
"\n\n Height:" + this.heightPerson +
"\n\n BMI Score:" + SetBmi().ToString();
}
}
}
Code (Part 2) Updated Mk 2
namespace Calculator
{
public class App
{
public static void Main() //
{
decimal heiP, weiP;
heiP = InputHeight();
weiP = InputWeight();
BMICalc bmiCal = new BMICalc(weiP, heiP);
Console.Clear();
Console.WriteLine(bmiCal.ToString());
Console.ReadKey();
}
public static decimal InputHeight()
{
decimal hNumber;
Console.Write("Please enter your height: ");
hNumber = Convert.ToDecimal(Console.ReadLine());
return hNumber;
}
public static decimal InputWeight()
{
Decimal wNumber;
Console.Write("Please enter your weight: ");
wNumber = Convert.ToDecimal(Console.ReadLine());
return wNumber;
}
}
}
You're input parameters into the constructor expects weight (weiP), height (heiP) (in that order) while you're passing height, weight from BMICalc bmiCal = new BMICalc(heiP, weiP);
That's the reason the value being output is incorrect. Interchange the parameters and it should be fine.
EDIT
Since you're entering the weight in Lbs and height in feet, you would need to convert feet into inches ( multiplying by 12) and then also multiplying the height and weight by the conversion metric.
So the formula would be:
bmi = Convert.ToDecimal((this.weightPerson * 0.45) / ((this.heightPerson * 12 * 0.025) * (this.heightPerson * 12 * 0.025)));
The currency comes in when it uses the ToString() overridden method. The format specified there is for currency.

Categories