Sean Probyn Sean Probyn - 1 year ago 78
C# Question

how do i check the result is between two numbers?

I have read the second line in a text file which contains

and I am trying to get it to do something if it meets certain criteria. I'm sure I have done this before and has a simple answer but I can't seen to figure it out.

string SecondLine;
using (var reader = new StreamReader(SPFile2))
SecondLine = reader.ReadLine();
int NewValue;
NewValue = Convert.ToInt32(SecondLine);
if ((NewValue >= 2) && (NewValue <= 2.99))
// Do Something
if ((NewValue >= 3) && (NewValue <= 3.99))
// Do something else

What have I missed out?

Answer Source

You are converting a decimal number to an Int32 that does not hold decimals. This will turn the number in NewValue into 2 as it truncates towards zero. You need to store the variable in a double, float or decimal whichever is best for your requirements.

See the following example that uses a double and Parse:

double newValue = Double.Parse(secondLine);

Note that if you are unsure if the value will be a double you should use Double.TryParse

double newValue;
bool result = Double.TryParse(secondLine, out newValue);
if (!result) //Parse failed

Note that if the parsing fails it may be down to your culture settings i.e. a ',' for the decimal separator not a '.'. However there is an overload for Parse and TryParse that allows you to pass culture information in.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download