Click here to Skip to main content
15,893,594 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hello!

I wanted to convert to float. I know, it is very simple thing to do, but it's harder to find a solution to this problem...
So heres the code:
C#
string s = "1.1"
float f = float.Parse(s);



Now I get a formatexception. I can't figure out why?!
Posted

The most likely reason for your error is that your regional settings use a different character for . (decimal point)

Try:

C#
float.Parse(s, CultureInfo.InvariantCulture);
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 25-Jan-11 13:29pm    
Yes, this is what I mean - my 5.
Sergey Alexandrovich Kryukov 25-Jan-11 14:20pm    
velvet7: will you formally accept this or both answers? You got all you need.
Nish Nishant 25-Jan-11 14:21pm    
Yeah there's not much incentive for marking a post as answered, is there?
Sergey Alexandrovich Kryukov 25-Jan-11 15:59pm    
:-)
GenJerDan 25-Jan-11 14:24pm    
Oooooo. I wonder how difficult that would be to code: to prevent a new question until your old one is closed. 8-)
This code works as you expect if you add missing ";" after first line — in default culture.
What is your thread culture? Maybe "," is expected as fraction delimiter (decimal point) — due to different culture?
 
Share this answer
 
v2
Comments
Espen Harlinn 25-Jan-11 15:12pm    
5+ Nice answer to one of the frequently asked questions
Sergey Alexandrovich Kryukov 25-Jan-11 15:17pm    
Really? That's funny.
Thank you,
--SA
CPallini 25-Jan-11 15:30pm    
The actual code already has the ';' (otherwise he couldn't get the 'format exception').
BTW: nice answer.
Sergey Alexandrovich Kryukov 25-Jan-11 15:51pm    
Of course it has ';' -- who would doubt? but not the text in Question.
Thank you.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900