Feretro
November 25, 2019, 2:43pm
1
Hello!
I’d need to convert properly a string value to a float.
I have a string, let’s say “6.5” but when I use
float number = float.Parse(Database.database.kmh_0_100[index1]));
“float” is 65, not 6.5
What can I do to get the right value?
Thank you so much!
You should verify that the value you are getting is 6.5 before you parse it. That is, the value of Database.database.kmh_0_100[index1]
Feretro
November 25, 2019, 3:03pm
3
Hello Brathnann and thanks for your help!
I verified and yes … the value is 6.5 … I will paste my code and sorry … It’s in italian but you will get it right!
Debug.Log("KMH DA PASSARE ORIGINALE: " + Database.database.kmh_0_100[index1]); // THIS IS THE ORIGINAL VALUE
Debug.Log("KMH DA PASSARE PARSE: " + float.Parse(Database.database.kmh_0_100[index1])); // THIS IS PARSED VALUE
// AND THIS IS THE PARSED
In attachment I uploaded what the Debug.Log shows!
Is it using the European style number formatting (where the usage of , and . is swapped)?
Give this a shot (I haven’t used this, but it looks like this is how it’s used):
float number = float.Parse(Database.database.kmh_0_100[index1], new CultureInfo("en-US") );
1 Like
Baste
November 25, 2019, 3:25pm
5
All string parsing in C# is culture-specific by default. To get sane results, you’ll want to always use the “invariant” culture.
So:
float number = float.Parse(Database.database.kmh_0_100[index1]), CultureInfo.InvariantCulture);
The alternative is that what the string parses to is dependent on your computer’s language, which is garbage .
EDIT: @StarManta beat me to it, but I really recommend using CultureInfo.InvariantCulture over trying to remember the CultureInfo strings.
2 Likes
Beaten to it by two people. I was thinking it might be a culture thing after you mentioned Italian.
Feretro
November 25, 2019, 4:48pm
7
Hey Thanks a lot for your help! I still can’t sort it out!
Both of “CultureInfo” solutions give me 6,5 from 6.5 … and I guess I can’t use 6,5 in my script!
Baste
November 25, 2019, 6:00pm
8
Both the input and the output is culture-dependent. So if you try this:
Debug.Log("Test: " + 6.5);
It’ll probably output “6,5”, not “6.5”.
To fix that, you’ll have to do the same thing when you print:
Debug.Log("Test: " + 6.5.ToString(CultureInfo.InvariantCulture));
All of this is of course an utter pain in the butt, and honestly Microsoft can go fuck themselves . Defaulting the culture to the user’s OS’ culture won’t help anyone make software be more global, it’ll just make software not work occasionally.
2 Likes
Feretro
November 25, 2019, 6:18pm
9
Baste:
Both the input and the output is culture-dependent. So if you try this:
Debug.Log("Test: " + 6.5);
It’ll probably output “6,5”, not “6.5”.
/Code]
You’re right! Thank you! And thanks to all that helped me!