Search code examples
c#type-conversionstring-conversion

Strange Behavior In C#: Parsing Strings To Doubles Bug


Update:

Here is a link to a project that fails at be even if it's explicitly a double in VS 2015 CE .NET 4.6. https://dl.dropboxusercontent.com/u/20941617/Scratchpad.zip

Ok I know how to replicate it. When it breaks on the the explicit operator chunk of code, you just have to copy the string straight out of debug and paste it in 'a' and it will break even though it looks like a normal string.

double a = double.Parse("1");
double b = double.Parse("1");

Original:

Why does 'a' work but 'b' throws an exception: "Input string was not in a correct format."?

double a = double.Parse("1");
var b = double.Parse("1");

The same exception occurs in the scenario below as well.

Number n = (Number)"‎1";

Number is a custom data type (struct) I made. It fails to parse the string into a double.

public static explicit operator Number(string n)
{
        double x = double.Parse(n);
        return new Number(x);
}

What is even more strange is I copied my struct into a new project I made to replicate the errors. But... in the original project with the same struct, it doesn't throw an exception.

I load constants from a text file and convert them to Number just fine. These constants work:

pi,3.14159265358979323846,none
π,3.14159265358979323846,none
golden ratio,1.61803398874989484820,none
phi,1.61803398874989484820,none
φ,1.61803398874989484820,none

But when it gets to this constant it throws the same exception.

Euler's constant,0.577215664901532860606512,none

It also throws it on "0.1", but not all the time... It's really confusing, which is why I made a new project, but it behaves differently in the new project for some reason.

I am using .NET 4.6 in all projects. I was using 5.4.2 originally but changed it. The issue appears to be the same in both versions.


Solution

  • this is the usual copy/paste issue of a hidden character

    in your code, the length of "1" for b is 2 characters

    the first chacracter is the unicode 8206 while the second one is 49 which is 1

    do some cleaning and it should work