Jason Chen
Jason Chen

Reputation: 2577

If Statement for Floats?

How do I make If statements using floats? The code I have is as follows:

{float p1 = float.Parse(textBox1.Text);
if (p1 == ""){MessageBox.Show("Home");}}

The p1 if statement on the second line does not work. How do I make a proper if statement for this?

EDIT: I should explain. The goal is to check for an empty box. I can't use a string command since I want this to interpret numbers.

Thanks in advance for the help.

Upvotes: 0

Views: 415

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

float values cannot be "empty". If you try parsing an empty string into a float, you would get a runtime error.

You need to check the string for being empty before parsing, and then parse with a more "conservative" TryParse method that does not throw an exception.

if (string.IsNullOrWhitespace(textBox1.Text)) {
    MessageBox.Show("Home");
}
float p1;
if (!float.TryParse(textBox1.Text, out p1)) {
    MessageBox.Show("textBox1 is not a float");
}

Note: In general, comparing floats for equality with == operator is not a good idea, because float is not an exact representation. This Q&A discusses the problem in Java, but the issue is relevant in all languages that use floating point representation.

Upvotes: 4

grovesNL
grovesNL

Reputation: 6075

If you are attempting to check whether or not it was able to successfully parse a float value from textBox1.Text, use TryParse instead like so:

float p1;
if (float.TryParse(textBox1.Text, out p1))
{
    MessageBox.Show("Home");
}

If you're simply trying to check for an empty text box, you could do this instead:

if (!String.IsNullOrEmpty(textBox1.Text))
{
    // Now we can try to parse p1 (assuming it's a valid number)
    float p1 = float.Parse(textBox1.Text);
    MessageBox.Show("Home");
}

Note that you would also have to handle invalid characters this way (such as letters, symbols, or spaces).

Upvotes: 2

Related Questions