Why does double.TryParse(“6E02”, out tempDouble) return true?

依然范特西╮ 提交于 2020-01-17 18:09:34

问题


It took me a day to figure out the problem that one of the if statement returns true for a string value.

We are parsing to check whether the value is a number or a string. I found out that this statement used and when the string value comes in as 6E02 the statement return true that this is a double value.

var double temp;
var val ="6E02"
result = double.TryParse(val, out temp)

How can I fix this issue to return the result false for strings like (Number)E0(Number)

Easy way I believe to check the text first if it contains E0 and if it does just return false. But is there a better way of handling this or another built in method to replace the method with?


回答1:


By default, double.TryParse uses the following flags from NumberStyles:

  • NumberStyles.AllowThousands
  • NumberStyles.Float, which is an alias for the following combination:
    • NumberStyles.AllowLeadingWhite
    • NumberStyles.AllowTrailingWhite
    • NumberStyles.AllowLeadingSign
    • NumberStyles.AllowDecimalPoint
    • NumberStyles.AllowExponent

You can use the other overload of TryParse to specify only a subset of these to your liking. In particular, you want to remove (at least) the AllowExponent flag.




回答2:


6E02 is scientific notation for 6*10^2 or 600, which is certainly a double. This is built into C#.

If you want to exclude numbers with scientific notation, there is an overload to TryParse that has several options, one of which is whether to include scientific notation or not.

var double temp;
var val = "6E02";
result = double.TryParse(val, NumberStyles.None, CultureInfo.CurrentCulture, out temp);
....

This example takes no styles, which means only strings with digits will be parsed. There are other options you can include as mentioned in Sam's answer.

You also have to specify a culture with this overload; my example uses the app's current culture, but you can explicitly give it whatever you want.




回答3:


It returns true because it sees it as scientific notation, as noted here:

An uppercase or lowercase character 'e', that indicates exponential (scientific) notation.

The easiest way is to probably just check if the string contains the letter e:

if(val.ToLower().Contains("e"))
{
    //Remove the letter, or parse it in a different way.
}


来源:https://stackoverflow.com/questions/26428080/why-does-double-tryparse6e02-out-tempdouble-return-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!