Reputation: 3
I have just made a program to calculate the total cost of an item or items given the quantity and price. One of my concerns is in the Cost of Item field, it does not accept decimals at all. I would also like both fields to not accept letters. I have seen something about TryParse
but I am unsure of how to use this and how it works. Any help is appreciated.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuantityPrice
{
class Program
{
static void Main(string[] args)
{
int Quantity;
int Cost;
Console.WriteLine("How much is the item you are buying? (In Canadian Dollars)");
Cost = int.Parse(Console.ReadLine());
Console.WriteLine("How many of the item are you buying? (In Canadian Dollars)");
Quantity = int.Parse(Console.ReadLine());
var TotalCost = Quantity * Cost * 1.13;
Console.WriteLine("Your total cost is:");
Console.WriteLine("$" + TotalCost);
Console.ReadLine();
System.Threading.Thread.Sleep(100000);
}
}
}
Upvotes: 0
Views: 1373
Reputation: 9318
You need to use decimals instead of int and to get the value, just ask for it as long as it is not a valid decimal like in this answer Need help with accepting decimals as input in C# that you could use directly like this:
var cost = RequestDecimal("How much is the item you are buying? (In Canadian Dollars)");
Use an equivalent function to get an int for quantity
Upvotes: 0
Reputation: 14376
The problem is you are using int.Parse
to extract the values from the user input. The int
type is only for integers. If you want to handle decimals, use either float
or double
(for general mathematics where you want a floating decimal point) or decimal
(for fixed point arithmetic such as currency).
As a general style comment, use "camel case" (starting with a lower case character) for variable names instead of "Pascal case" (starting with an upper case character).
Upvotes: 1