Sean Probyn Sean Probyn - 9 days ago 6
C# Question

how do i check the result is between two numbers?

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

2.75
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))
{
reader.ReadLine();
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

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.

Comments