views:

353

answers:

1

This is kind of related to my previous question, but not really. I have an input of which I don't know the culture. So it can both use ',' and '.' as separator for the fraction. The number will never be >5 though, so we can be rather sure if there's a separator, it will be for the fraction.

I was looking at the TryParse method. It accepts a NumberStyles argument. But I don't see anything about fraction separator or the like..

Am I missing something again or is there a better way to reach my goal?

+8  A: 

Try this:

float.TryParse(myString.Replace(',', '.'), out myfloat);

EDIT: as Jon mentioned, the following way is recommended:

float.TryParse(myString.Replace(',', '.'), 
               System.Globalization.NumberStyles.Float, 
               System.Globalization.NumberFormatInfo.InvariantInfo, 
               out myFloat);
Mehrdad Afshari
If you explicitly want to use "." as the separator, I'd pass in CultureInfo.InvariantCulture as well.
Jon Skeet
This can fail if there are also thousant separators.
Gamecat
@Jon: Good point.
Mehrdad Afshari
@Gamecat: The question says the number is less than 5.
Mehrdad Afshari
Gamecat - that's exactly what I was just thinking! I guess you'd have to get to the end of the string and work backwards, treating the first , or . as the decimal separator and ignoring everything you subsequently found.
robsoft
@Mehrdad - oops. I skimmed that, too. :-)
robsoft
@Gamecat: Sure, but a number with a thousand separators is way too large (or rather, too small) to fit into a float anyhow.
Dana
@Dana, I think you are underestimating float type.
Mehrdad Afshari
@Mehrdad - I might be :P Can it actually store a fraction that small? With a thousand separators in it?
Dana
"1,234.5" is a valid float and it has a thousand separator.
Mehrdad Afshari
@Mehrdad - Haha, I misread GC! I read him as saying if there were a thousand commas it would fail :P As in 0.000,000,..[998 more commas]..,001
Dana
@Mehrdat Afshari, I know, but I just added the remark for if somebody else uses the solution without the constraint.
Gamecat
Mehrdad or someone else with enough points please edit the text to include Jon's hint with CultureInfo.InvariantCulture. Thanks.
Christoph Rüegg
@Christoph: Done.
Mehrdad Afshari