简体   繁体   中英

Check if string is equal to a double

String[] vals = s.Split(';');
String o = "X=" + vals[0] + "  Y=" + vals[1] + "  Z=" + vals[2];

I have this code to display the values of x,y,z. Now I want to implement if the x,y,z values = 225.0 . something would happen.

I can't just

double num = 225.0;
if (vals[0] = num ); 

It says, I cannot convert 'double' to 'string' . How should I do this ?

You could convert vals[0] to double with ConvertToDouble :

double num = 225.0;
if (Convert.ToDouble(vals[0], CultureInfo.InvariantCulture) == num)

If you want to check if all values in vals are equale to 225.0 you could use LINQ All :

if (vals.All(x => Convert.ToDouble(x, CultureInfo.InvariantCulture) == num))

DEMO HERE

Your question has more complexity than it seems. At first glance, the answer to the question "how do I compare a string with a floating point number" is "convert the string to a floating point number and then compare the numbers":

double num = 225.0;
if ( Convert.ToDouble(vals[0]) == num ) {
    // Do something
}

This however can cause subtle bugs that you might catch with some extensive testing, but that you might also miss. The reason is that floating point data types have a precision and comparisons for direct equality can yield false due to rounding errors, even when you expect the result to be true . A detailed description of the problem and how you overcome it can be found on this site .

In your case you should consider a simpler solution that will work in many cases in practice: Compare fixed point numbers. In the .NET framework this means comparing variables of type decimal :

decimal num = 225M;
if ( Convert.ToDecimal(vals[0]) == num ) {
    // Do something
}

There is still a problem in this code though, since the conversion is done based on the local culture of the host system. Usually, you want to compare based on a fixed culture:

decimal num = 225M;
if ( Convert.ToDecimal(vals[0], CultureInfo.InvariantCulture) == num ) {
    // Do something
}

If comparing with decimals doesn't work for you due to the nature of your data, you should consider a more complex floating point comparison as described in the linked article.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM