TryParse for numbers in C#? - c#

So I want to use a TryParse method, but so far I can do it only with integer or double value. However, I want to check if the value is a number, and if it's not (if it is a string for instance) to get a false value. Something like IsDigit() is Java.
static void Main()
{
int number;
Console.Write("Enter a number: ");
bool result = Int32.TryParse(Console.ReadLine(), out number);
if (result)
{
Console.WriteLine("The input number is an integer.");
}
else
{
Console.WriteLine("The input number is not an integer.");
}
}
So I want to do that, but instead of checking for an integer value, I'd like to check for a numerical value. So if anybody can tell me what method I can use I'd be very happy.
Thanks in advance!

use double:
double number;
bool result = double.TryParse(Console.ReadLine(), out number);
This will parse any real number.

TryParse for decimal or double types is your limit for built in methods. If you want more than that, you'd have to parse the string yourself. The can be quite easily done using a regex, such as
^-?[0-9]+\.?[0-9]*([Ee][+-]?[0-9]+)?$

bool result = double.TryParse(mystring, out num);
The double.TryParse also works on integers.

For a single character, there's Char.IsDigit(). In that case you may want to look at Console.ReadKey() instead of reading a whole line. By the way, Char.IsDigit() also matches digits from other cultures.
For multiple characters you'll need to think about what you want to accept. decimals, exponents, negative numbers, or just multiple digit characters?

You could try a regular expression
var regex = new Regex(#"^-*[0-9\.]+$");
var m = regex.Match(text);
if (m.Sucess)
{
Console.WriteLine("The input number is an integer.");
}
else
{
Console.WriteLine("The input number is not an integer.");
}
You can also allow separators by including them in the regex.

static bool enteredNumber()
{
int intValue;
double doubleValue;
Console.Write("Enter a number: ");
string input = Console.ReadLine();
return Int32.TryParse(input, out intValue) ? true : double.TryParse(input, out doubleValue);
}

Related

Check string is decimal with 2 decimal places

I have a textbox that a user enters a number into. I need to ensure that the number is at most 5 numbers before the decimal place and mandatory 2 digits after. The number must always have 2 digits after the decimal point. What Regex could I use to check this? (The solution is in C#)
Something like this:
String source = ...;
if (Regex.IsMatch(source, #"^[0-9]{,5}\.[0-9]{2}$")) {
//TODO: put relevant code here
}
If you want at least one digit before decimal point, the pattern will be
#"^[0-9]{1,5}\.[0-9]{2}$"
Just Try this code
string Value= "12345.63";
if (Regex.IsMatch(Value, #"^[0-9]{5}\.[0-9]{2}$"))
{
Console.WriteLine(Value);
}
else
{
Console.WriteLine("Not Match");
}
Console.ReadKey();

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.
}

Regex C# console app

How do I add a regular expression which will accept decimal places (5.23) but nothing else in a break like so? i.e handle only numbers and decimal places which will throw an error if anything other than this is typed or returned:
case 1:
double[] myArrai1 = new double[3];
Console.WriteLine("Insert a number");
myArrai1[0] = double.TryParse(Console.ReadLine()); // no overload method?
Console.WriteLine("Insert a number");
myArrai1[1] = double.Parse(Console.ReadLine());
Console.WriteLine("Insert a number");
myArrai1[2] = double.Parse(Console.ReadLine());
break;
Cheers guys.
P.s not sure on how to programme it in with the break also has to be without exception.
Regex is a little heavy for validating a double. Use double.TryParse instead (it'll return false if the input is invalid).
double dbl;
if (!double.TryParse(Console.ReadLine(), out dbl))
Console.WriteLine("Invalid input");
You don't need a Regex for this.
You can simply use decimal.Parse or double.Parse - if the input string is in the wrong format, you will get a FormatException.
The code you posted appears to be right - what's not working?
try this :
/^\d+(\.\d{1,2})?$/;
Regex regex = new Regex ("^\d+(\.\d{1,2})?$");
MatchCollection matches = regex.Matches(text);
if (matches.Count>0)......
You will probably be better off just using .NET's double parsing instead of trying to re-invent it in Regex. You can use Double.TryParse to test the string and do the conversion if the number can be parsed:
Console.WriteLine("Insert a number");
string input = Console.ReadLine();
double value;
if (!Double.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
throw new InvalidOperationException(String.Format("{0} could not be parsed as a valid number.", input));
Did you want to just validate what the user inputs, or stop them from putting in invalid characters in the first place?
In the first case, regex aren't really needed. You are on the right track with double.Parse, but what you want to do is double.TryParse. First read the user input into a string, then TryParse it into a double. If TryParse returns false, tell you user their input is invalid and prompt them to enter it again.
FWIW: here's how I'd do it (warning: untested code), which may or may not be what you need:
case 1:
double[] myArrai1 = new double[3];
for (int i=0; i < myArrai1.length; i++) {
Console.WriteLine("Insert a number");
while (!double.TryParse(Console.Readline(), out myArrai1[i])) {
Console.WriteLine("Invalid entry. Please enter a number.");
}
}
break;

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

Char tryParse not working as I thought?

I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.

Categories