Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a double value from a string

Tags:

c#

.net

double

I've tried to solve this for hours and absolutely don't understand what the compiler is doing here. I have strings that basically look like this:

"KL10124 Traitor #2 - +XX-+0.25 - More Stuff"

and need to read off the double '0.25' programmatically. Calling the string above s, the following two lines don't work:

string[] h = s.Split('-');
string h2 = h[2].Substring(1,h[2].Length - 2);
double d = Convert.ToDouble(h2);

The output if I display d is "25". I thought it might depend on the '.' resp ',' culture dependency, but if I insert

double d = Convert.ToDouble(h2.Replace('.',','));

it does not change a thing, the output is still "25".

But finally, if I do the brute force method as below I get the verbatim output "0,25" on the screen

double d;
string[] h = s.Split('-');
string h2 = h[2].Substring(1,h[2].Length - 2);
if (h2.Contains("."))
{
    string[] h3 = h2.Split('.');
    d = Convert.ToDouble(h3[0]) + Convert.ToDouble(h3[1])/100;
}
else
{
    d = Convert.ToDouble(h2);
}
return d;

Why exactly do the first two versions not work? The last bit of code cannot be the correct way to do this.

like image 697
EluciusFTW Avatar asked Nov 28 '25 06:11

EluciusFTW


1 Answers

Try to use

double d = Convert.ToDouble(h2, CultureInfo.InvariantCulture);

instead of

double d = Convert.ToDouble(h2);
like image 107
Ilya Ivanov Avatar answered Nov 30 '25 21:11

Ilya Ivanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!