Lutske
Lutske

Reputation: 117

c# string to float convert doesn't work correct

I have to convert a string to a float, only the normal converters don't work.

fi.Resolution = float.Parse(nodeC.InnerText);
fi.Resolution = (float)nodeC.InnerText; 
fi.Resolution = Single.Parse(nodeC.InnerText);

and more of those methods don't work. When the nodeC.InnerText is 0.01 it returns 1, but if nodeC.InnerText is 5.72958e-07 it returns 0,0575958 and 0.0001 also returns 1, so it isn't that it bitshifts.

Does anyone know why this standard c# converts don't work?

So i'm trying to write my own StringToFloat method but it fails :P

public float StringToFloat(string input)
        {
            float output = 0;
            char[] arr = input.ToCharArray();

            for (int i = 0; i < input.Length - 1; i++)
            {
                if (arr[i].Equals("."))
                    output += 1;//change
                else
                    output += Convert.ToInt32(arr[i]);
            }

            return output;
        }

Upvotes: 2

Views: 1193

Answers (2)

Stilgar
Stilgar

Reputation: 23591

Do you by any chance use Windows locale that defaults to "," as the decimal separator?

also:

(float)nodeC.InnerText; 

should never work

Upvotes: 1

Rawling
Rawling

Reputation: 50184

Try fi.Resolution = float.Parse(nodeC.InnerText, CultureInfo.InvariantCulture);

It looks like your current culture is expecting , as the decimal separator and ignoring any . present.

Hence

0.01        =>    001     => 1
5.72958e-07 => 572958e-07 => 0,0572958 (note it gave you a , not a .)

Upvotes: 10

Related Questions