Why does double.TryParse(“6E02”, out tempDouble) r

2019-09-30 06:32发布

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?

3条回答
不美不萌又怎样
2楼-- · 2019-09-30 06:49

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-09-30 06:56

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.

查看更多
看我几分像从前
4楼-- · 2019-09-30 07:03

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.
}
查看更多
登录 后发表回答