Here's my problem, I'm trying to format a {"C:O"} into a console.readline but I'm getting a method name expected error. here's what I have now:
money = double.Parse(Console.ReadLine()(string.Format("{O:C}")));
In addition to the syntax errors, you should generally use decimal to represent money, since many operations on double can result in round-off errors.
I'd recommend something like this:
string input = Console.ReadLine();
decimal money = decimal.Parse(input);
Or in one line:
decimal money = decimal.Parse(Console.ReadLine());
But Parse will throw an exception if given invalid input (e.g. "foo"). You might want to use TryParse to be a bit safer:
decimal money;
if (!decimal.TryParse(Console.ReadLine(), out money))
{
Console.WriteLine("Invalid input");
}
Related
I am trying to take the string input of TR and string PMP convert them into currency then multiply together to get an output in USD currency .
string SP; // Sales Price
string TR; //Total Revenue
string PMP; //Property management percentage
string PMF; //Property Management Monthly Fee
Console.WriteLine("What is the total rent revenue?");
TR = Console.ReadLine();
Console.WriteLine("what is the percentage you pay to property managment?");
PMP = Console.ReadLine();
Console.WriteLine("you will be buying {0}", PMF );
SP = Console.ReadLine();
TR = Console.ReadLine();
PMP = Console.ReadLine();
PMF = string.Format("{TR:C,PMP:C}") <------- THIS IS WHERE I AM TRYING TO CONVERT AND MULTIPLY****
Any help will be grateful. Thank you
PS I am not a programmer by trade (mostly Networking Engineering and Server Admin), This is my first 20 hours into programming.
If it were me, I would start by creating a method to get a valid decimal number from the user (because we do this several times, and it should have some error handling for cases when the user enters invalid entries). Something like:
public static decimal GetDecimalFromUser(string prompt,
string errorMessage = "Invalid entry. Please try again.")
{
decimal value;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (decimal.TryParse(Console.ReadLine(), out value)) break;
if (errorMessage != null) Console.WriteLine(errorMessage);
}
return value;
}
Then, I would call this method to get the input from the user, do the required calculation (you didn't specify a formula, so I'm improvising), and output the value to the user:
decimal totalRevenue = GetDecimalFromUser("Enter the monthly rent revenue: $");
decimal propMgmtPct = GetDecimalFromUser("Enter the percentage you pay " +
"for property management: ");
decimal propMgmtFee = totalRevenue * propMgmtPct;
Console.WriteLine("The monthly property management fee will be: {0}",
propMgmtFee.ToString("C2", CultureInfo.CreateSpecificCulture("en-US")));
The Format syntax is more like string.Format("{0:C},{1:C}", TR, PMP).
You can only format numeric types such as decimal like that. Consider decimal.TryParse to see if what the user typed, looks like a number, then format the resulting number.
For multiplication you certainly need numeric types, like decimal, and you use the asterisk symbol * as the multiplication operator.
I have a snipped of code that I wrote that calculates how long the user has been alive. But the problem is, the program goes to hell if the user doesn't enter a integer e.g January or something else. I need to know how to stop this.
int inputYear, inputMonth, inputDay;
Console.WriteLine("Please enter the year you were born: ");
inputYear = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the Month you were born: ");
inputMonth = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the day you were born: ");
inputDay = int.Parse(Console.ReadLine());
DateTime myBrithdate = new DateTime(inputYear,inputMonth, inputDay);
TimeSpan myAge = DateTime.Now.Subtract(myBrithdate);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
if the user doesn't enter a integer e.g January or something else
You can use Int32.TryParse method then..
Converts the string representation of a number in a specified style
and culture-specific format to its 32-bit signed integer equivalent. A
return value indicates whether the conversion succeeded.
Console.WriteLine("Please enter the Month you were born: ");
string s = Console.ReadLine();
int month;
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out month))
{
// Your string input is valid to convert integer.
month = int.Parse(s);
}
else
{
// Your string input is invalid to convert integer.
}
Also TryParse method doesn't throw any exception and that's why you don't need to use any try-catch block with it.
This is far above my level, I have no idea what is going on here.
Ok. I try to explain a little bir more deep.
What you complain is the users input right? Beucase you said, you want to put int as an input. Not string like "January" or "May" etc..
When you read input with Console.ReadLine() method, it returns a string as a return type, not int. Doesn't matter user put as an input 3 or January, this method returns them as a string regardless what they are type is.
3 and January are strings in this case. But how we check these strings are actually convertable to an integer value? This is the part of why we using Int32.TryParse method. This method checks these inputs are convertable to integers or not so we can use this integer in DateTime constructor as a real integer.
This is because you are using int.Parse(Console.ReadLine()); - the int stands for integer. Well you could put a try catch block arround your code.
The original code would stand in the try block, because you want to try to run it- but if an error accours ( e.g. user types jan), the catch block handles the error and your program could go on without troubles.
I have a Windows forms application written in C#.
I am looking for a way to validate my price textBox so that it only accepts prices in a double format e.g. allowing 0.01 & 1200.00 but provides an error when the user enters characters.
I would except the code to looks similar to
String price = tbx_price.Text.Trim();
if price is not a number
{
error message
}
else{
...
What method could I use to check if the price string contains only numbers? Please note that I require the user to be able to use decimal places so the '.' character should be allowed.
Use decimal.TryParse :
decimal d;
if (!decimal.TryParse(price, out d)){
//Error
}
And if you also want to validate the price (145.255 is invalid):
if (!(decimal.TryParse(price, out d)
&& d >= 0
&& d * 100 == Math.Floor(d*100)){
//Error
}
You can test this using decimal.TryParse().
For example:
decimal priceDecimal;
bool validPrice = decimal.TryParse(price, out priceDecimal);
If you can't be sure that the thread culture is the same as the user's culture, instead use the TryParse() overload which accepts the culture format (also the number format which you can set to currency):
public bool ValidateCurrency(string price, string cultureCode)
{
decimal test;
return decimal.TryParse
(price, NumberStyles.Currency, new CultureInfo(cultureCode), out test);
}
if (!ValidateCurrency(price, "en-GB"))
{
//error
}
Besides using the answer marked as accepted in order to avoid the problem with culture about prices, you can always use this
Convert.ToDouble(txtPrice.Text.Replace(".", ","));
Convert.ToDouble(txtPrice.Text.Replace(",", "."));
this will depend how you manage your convertion in your app.
PS: I could not comment the answer because i do not have the neccesary reputation yet.
I have another question about the TryParse method I have created to check for my user's input. Sorry for my extra question, but I ran into another complication and wanted more assistance on it, so I made another question since my last one is quite old. I was afraid no one would see this question if I post it on the last one.
There are no errors, but when I try to run it to test what my user's input, for everything I enter, including whole numbers, decimals, (1.00, 1.0, 1,000.0) it gives me the Messagebox.Show anyway. Here's what I created:
{
// Arrange the variables to the correct TextBox.
decimal Medical;
if (!decimal.TryParse(ChargeLabel.Text, out Medical))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Surgical;
if (!decimal.TryParse(ChargeLabel.Text, out Surgical))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Lab;
if (!decimal.TryParse(ChargeLabel.Text, out Lab))
{
MessageBox.Show("Please enter a decimal number.");
}
decimal Rehab;
if (!decimal.TryParse(ChargeLabel.Text, out Rehab))
{
MessageBox.Show("Please enter a decimal number.");
}
// Find the cost of Miscs by adding the Misc Costs together.
decimal MiscCharges = Medical + Surgical + Lab + Rehab;
ChargeLabel.Text = MiscCharges.ToString("c");
In other words, I try to input any form of numbers on the Medical, Surgical, Lab, and Rehab textboxes and it still gives me the same MessageBox. Will someone provide me help on how to let my application check my user's input correctly? Thanks you, and sorry again.
Make sure that you are entering numbers in a culture-correct format. Some cultures use comas as separators, others use dots. Try "123,4" and "123.4"
You are using the same label in each parsing statement.
decimal.TryParse(ChargeLabel.Text, out Medical)
decimal.TryParse(ChargeLabel.Text, out Surgical)
decimal.TryParse(ChargeLabel.Text, out Lab)
decimal.TryParse(ChargeLabel.Text, out Rehab)
EDIT I'd recommend putting a breakpoint in each MessageBox.Show line, then seeing what the string value you're parsing is.
You can also provide more information in the message shown:
decimal Rehab;
if (!decimal.TryParse(ChargeLabel.Text, out Rehab))
{
MessageBox.Show(string.Format("Unable to parse '{0}' as a decimal number.", ChargeLabel.Text));
}
It seems that sometimes the currency format does not work:
string Amount = "11123.45";
Literal2.Text = string.Format("{0:c}", Amount);
reads 11123.45
it should be:
$11,123.45
That code would never work - because Amount is a string, not a number. The currency format only applies to numbers.
For example:
decimal amount = 11123.45m;
Console.WriteLine(string.Format("{0:c}", amount);
(Note that using double for currencies is almost always a bad idea, as double can't exactly represent many decimal numbers. Decimal is a more appropriate type for financial data.)
It's because Amount is a string instead of a numeric.
This worked for my situation
string Amount = "11123.45";
amount2 = amount.AsDecimal();
string.Format("{0:c}", #amount2)