c# parse string to float

Soldato
Joined
30 Nov 2005
Posts
13,915
i need to parse a string which the user has inputed to a float value so I can do some calculations on it. But it kind of got me stumped .
any ideas?
 
you might want to use this instead, unless you know that your string is going to be a valid float value:

Code:
string str = "3.14159";
float fnum;
bool result = float.TryParse(str, out fnum);

TryParse will return true if string is valid, and false if not, and irc, this will also set fnum to zero if the string isn't a valid float value, the other code would just throw an exception :(

oh and don't miss out the out :)
 
yes you could :) depends on your style of coding though I guess, I prefer the method I use but the guys in the office prefer the try catch method because it easier to see what's going on :)

Generally you should use float.Parse if you're expecting input to be valid and if invalid input will cause terminal problems, and float.TryParse if invalid input is expected/won't cause problems. It's a matter of semantics really though.
 
Exceptions are fairly expencive, so I think its not only 'better looking' but more efficient to use tryparse.

While I agree that exceptions probably aren't the way to go here, I'd disagree that performance is a valid reason; exceptions are not as expensive as people think, and avoiding them for the sake of performance is almost always premature optimization. Have a read:

http://www.yoda.arachsys.com/csharp/exceptions2.html
 
I prefer exceptions to return codes, you can put more information in an exception, and it leaves all the if(status == 1) statements out.
 
While I agree that exceptions probably aren't the way to go here, I'd disagree that performance is a valid reason; exceptions are not as expensive as people think, and avoiding them for the sake of performance is almost always premature optimization. Have a read:

http://www.yoda.arachsys.com/csharp/exceptions2.html
I've done my own tests and in situations where exceptions are thrown on a regular basis, the performance is terrible. If I remember my figures from a test (took a big file with ~10m piece of information - roughly 30% were not numbers, and recorded how long it took tryparse and exceptions to churn through it). The tryparse method was about 50x faster or somewhere abouts.

Basically exceptions (imo) should be thrown in exceptional situations only. If there is something to do with user input or a half decent chance unexpected data could be coming in I will always check the data rather than relying on exceptions.

I guess the main point is in many situations the number of exceptions won't cause performance issues as it might be a stand alone app, but on a website with thousands of users or something time critical, it wouldn't be a great idea.

all imo :}
 
Back
Top Bottom