简体   繁体   English

检查字符串是否等于double

[英]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. 我有这个代码来显示x,y,z的值。 Now I want to implement if the x,y,z values = 225.0 . 现在我想实现x,y,z值= 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' . 它说,我不能将'double'转换为'string'。 How should I do this ? 我该怎么做?

You could convert vals[0] to double with ConvertToDouble : 您可以使用ConvertToDoublevals[0]转换为double:

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 : 如果你想检查是否在所有值vals是equale至225.0你可以使用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 . 其原因是,浮点数据类型有直接的平等精度和比较可以产生false由于舍入误差,甚至当你希望得到的结果是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 : 在.NET框架中,这意味着比较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. 如果由于数据的性质,与小数比较不适合您,您应该考虑更复杂的浮点比较,如链接文章中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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