How to Read decimal numbers from a user in C#? - c#

so I'm 3 weeks new to programming and I am trying to make a basic Console calculator using C#. I do not know how to read a decimal (eg. 5.5) from a user. Normal integers (e.g. 5) work though. I get the below exception error:
An unhandled exception of type 'System.FormatException' occurred in
mscorlib.dll
Additional information: Input string was not in a correct format.
This is the code:
Console.WriteLine(
"Hi there, My name is Mohammed.\n" +
"Today we are going to be doing several calculations.\n\n" +
"These would include Addition, Subtraction, Multiplication and Division. ");
Console.WriteLine("To get started, please hit the space key.");
Console.ReadKey();
Console.WriteLine("We will start with a addition. Please enter the first number.");
double num01 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Now enter the second number");
double num02 = Convert.ToDouble(Console.ReadLine());
double ans01 = (num01 + num02);
Console.WriteLine(num01 + "+" + num02 + " is equals to " + ans01 +
"\nGreat, now lets move on to subtraction. Please enter the first number.");

I suggest method extraction, something like this:
using System.Globalization;
...
private static double ReadDouble(string title)
{
while (true)
{
Console.WriteLine(title);
string userInput = Console.ReadLine();
double result;
// We use CultureInfo.InvariantCulture to ensure that
// decimal separator is dot (.). i.e. we expect 5.5 input
if (double.TryParse(userInput,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out result))
{
return result;
}
Console.WriteLine("Sorry, incorrect format. Enter it again, please.");
}
}
Then we can use the routine
...
Console.ReadKey();
double num01 = ReadDouble("We will start with a addition. Please enter the first number.");
double num02 = ReadDouble("Now enter the second number");
double ans01 = (num01 + num02);
...

You should check the current culture on your computer. You can go to Control Panel and click Region and Language. From there, click Additional settings button at the bottom. It should take you to the Customize Format page like below
This page tells you how to enter a decimal number on your console. The above steps are for Win 7 machine. You can then try the following C# code to verify the working from the immediate window on Visual Studio
double.Parse("5.5");
double.Parse("5,5");
The correct format will not throw an Exception in the immediate window (or temp code)
Also, the same Decimal symbol can be extracted via C# using the below code
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.PercentDecimalSeparator

Related

Error: Unhandled Exception: System.FormatException: Input string was not in a correct format

When typing the following code, the console opens and I can input a value but when I press a key the .NET crashes and the console shuts down
I've tried to type only "text" + input and $ at the start of "text"
using System;
namespace Programmeren1Week2
{
class Program
{
const double BTW = 0.21;
static void Main(string[] args)
{
Console.WriteLine("Geef prijs:");
Console.ReadLine();
double invoer = double.Parse(Console.ReadLine());
double metBTW = invoer * BTW;
Console.WriteLine($"De prijs is {0}:" + invoer, "de btw is {1}:" + BTW, "Totaalprijs is {2}: " + metBTW);
Console.ReadKey();
}
}
}
I managed to reproduce your issue by passing in a text value where you ask for input. If by
I've tried to type only "text" + input and $ at the start of "text"
You mean you are typing "text" when prompted for input, that's your problem.
Your invoer variable is a double, so it cannot accept strings as input. Try inputting a numerical value, and see if that fixes your problem.
That issue aside, there is one other thing that needs fixing.
As a few others have pointed out, you are formatting your string incorrectly. This will cause an issue if you fix your original error. To fix this, change that line to be:
Console.WriteLine($"The prize is {invoer}, the VAT is {BTW}: Total price is {metBTW}: ");
This should produce a functioning program.
It's probably that you are entering a string that cannot be parsed to a double in your ReadLine call.
If propose this alternative solution to handle this issue.
Console.WriteLine("Geef prijs:");
if(double.TryParse(Console.ReadLine(), out double invoer))
{
double metBTW = invoer * BTW;
Console.WriteLine($"De prijs is : {invoer} , de btw is : {BTW} , otaalprijs is : {metBTW}");
Console.ReadKey();
}
else
{
Console.WriteLine("Bad input");
}
Instead of using Parse use TryParse. (It returns true for valid values, and false for invalid values.) Use it like this:
double number;
if (Double.TryParse(Console.ReadLine(), out number))
{
// normal flow
}
else
{
// bad input (not a double, request another input)
}
Try this
Console.WriteLine(String.Format("De prijs is {0}: de btw is {1}: Totaalprijs is {2}: ", invoer, BTW, metBTW));
Or
This
Console.WriteLine($"De prijs is {invoer}: de btw is {BTW}:
Totaalprijs is {metBTW}: " );

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll error when using Parse

Newcomer to the world of programming, have to do the assignment listed here: Reading and processing input
Now, I've finally wrapped my head around how to write the code (seen below), but I keep on getting "An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll. Additional information: Input string was not in a correct format." when I try to run my program. It keeps flagging up on "gross = double.Parse(inputvaluetwo);", which is presume might be due to there not being an input there. Could anyone please help?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SalesProgram
{
class SalesProgram
{
static void Main(string[] args)
{
double sales;
double gross;
double retirement;
double social;
double tax;
string inputvalue;
string inputvaluetwo;
string inputvaluethree;
string inputvaluefour;
string inputvaluefive;
string name;
Console.Write("Enter your name: ");
name = Console.ReadLine();
Console.WriteLine("How much did you sell in dollars? ");
inputvalue = Console.ReadLine();
sales = double.Parse(inputvalue);
Console.ReadKey();
Console.WriteLine("Your gross pay is");
Console.ReadKey();
Console.WriteLine(sales * 0.07);
inputvaluetwo = Console.ReadLine();
gross = double.Parse(inputvaluetwo);
Console.ReadKey();
Console.WriteLine("Your retirement deduction is:");
Console.WriteLine(gross * 0.15);
inputvaluethree = Console.ReadLine();
retirement = double.Parse(inputvaluethree);
Console.ReadKey();
Console.WriteLine("Your tax deduction is:");
Console.WriteLine(gross * 0.18);
inputvaluefour = Console.ReadLine();
tax = double.Parse(inputvaluefour);
Console.ReadKey();
Console.WriteLine("Your social security deduction is:");
Console.WriteLine(gross * 0.09);
inputvaluefive = Console.ReadLine();
social = double.Parse(inputvaluefive);
Console.ReadKey();
Console.WriteLine("Finally, your take-home, or net pay, is:");
Console.WriteLine(gross-retirement-tax-social);
Console.ReadKey();
}
}
}
It means there's an incorrect string value somewhere. Use this instead :
double retirement ;
if(double.TryParse(inputvaluethree, out retirement) == false)
{
Console.Write("Error on inputvaluethree : " + inputvaluethree);
}
It means the string you entered can not be converted to double.
Use following snippet
if (Double.TryParse(string, out inputvalue))
{
//do any additional stuff you want to with this inputvalue
}
else
{
//do what you want to do if conversion fails
}
This overload differs from the Double.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value. It eliminates the need to use exception handling to test for a FormatException in the event that string is invalid and cannot be successfully parsed.
For more details you can go to following link
https://msdn.microsoft.com/en-us/library/994c0zb1%28v=vs.110%29.aspx

If value = text?

I'm trying to validate some data and I was wondering is it possible to encode an if statement so that if there is a text value entered instead of a numeric value that it does not crash?
Obviously the standard message indicating that an incorrect message has been entered.
I'll write an example here:
Console.WriteLine("Please enter your height in centimetres please.");
Console.WriteLine("My height is: ");
dHeight = Convert.ToDouble(Console.ReadLine());
if (dHeight == xxxxxx?)
{
Console.WriteLine("Sorry incorrect data entered, please enter a numeric value");
dHeight = Convert.ToDouble(Console.ReadLine());
}
What would I need instead of this as I am not sure how to phrase it/if it is indeed even possible.
You can go with double.TryParse method which will return false if your value cannot be parsed.
double result;
if (double.TryParse(yourstirng, out result))
{
//your string is double do something with the parsed value
result++;
}
else
{
Console.WriteLine("Sorry incorrect data entered, please enter a numeric value");
}
Sure, you can use TryParse, and then if it fails, prompt them again. Note I also added some retry logic here, so that the user cannot proceed until they enter a valid double.
In the code below, I capture their input in a variable (called input) and then use double.TryParse to try to convert it to a double. If the TryParse succeeds, then the double result will contain their converted entry. If it fails, then an error message is displayed and they can try again.
Console.Write("Please enter your height in centimeters: ");
var input = Console.ReadLine();
double result;
while (!double.TryParse(input, out result))
{
Console.Write("{0} is not a valid height. Please try again: ", input);
input = Console.ReadLine();
}
Console.WriteLine("Thank you. You entered a valid height of: {0}", result);
Convert.ToDouble uses double.Parse under the hood, which means that it will throw if an invalid format is encountered (ie. plain text).
Instead, use double.TryParse which does not throw if it fails (it simply returns false):
double dHeight = 0;
if (!double.TryParse(Console.ReadLine(), out dHeight))
{
Console.WriteLine("Some Error Message");
}
else
{
//Parse succeeded! Value is in dHeight.
}

Decimal TryParse fails when a Decimal is entered

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

Sum up Double ReadLine values?

I'm new to C# programming and I'm not sure what I'm doing wrong because I can't sum up numbers that are Double. If I input 2,5 and 2,5 I get 5, but if I enter 2.5 and 2.5 I get zero when I use a dot instead of a comma between the numbers. Why this?
I add some of my code:
private void ReadInputAndSumNumbers()
{
while (!done)
{
Console.Write("Number: ");
if (double.TryParse(Console.ReadLine(), out num))
{
if (num == 0)
{
done = true;
}
else
{
sum += num;
}
}
}
}
My settings are to use a comma, but I would like the user to be able to enter a value with dot also
How are you converting your ReadLine input into Doubles? Most of the conversion operations are locale-specific, so if your Windows settings have , as the decimal separator, this setting is respected.
Example:
string enteredByUser = Console.ReadLine();
// uses user-specific Windows settings (decimal separator might be ",")
double myDouble1 = double.Parse(enteredByUser);
// uses default settings (decimal separator is always ".")
double myDouble2 = double.Parse(enteredByUser, CultureInfo.InvariantCulture);
A short side note: If you parse user input, you should look into double.TryParse, since this is more robust than double.Parse or Convert.ToDouble, since it allows you to detect faulty input without resorting to exception handling.
EDIT: If you want to support both comma and dot, you need to convert dots into commas (or vice versa) first. String.Replace can help you here. Note, though, that this approach will break if the user tries to enter a thousands separator (1.000,00 -> 1.000.00 or 1,000,00 -> error). The recommended way to do it is to
only accept the decimal separator specified in Windows, if the input comes from an end-user (i.e., keep your code as it is) and
only accept the neutral culture (.), if the input comes from some machine-generated output or file.
A sample for caculate the double sum
static void Main(string[] args)
{
var retVal = 0.0;
var sum = 0.0;
while (true)
{
Console.WriteLine("Enter input:");
string line = Console.ReadLine();
if (line == "exit")
{
break;
}
double.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture, out retVal);
sum += retVal;
Console.WriteLine(string.Format("Double Value : {0}", sum ));
}
Console.ReadKey();
}

Categories