I have float number in string. there is one problem. Number uses "." not "," as decimal point.
This code is not working:
MyNumber = float.Parse("123.5");
I know that I can use string replace function to "repair" this string before Parsing.
MyNumber = float.Parse("123.5".Replace('.',',');
But is there any other way to do it?
To add to Steven's question, rather than argue differently, the important thing is why the decimal separator is
.
.If it's because the source is in a computer-readable format where the period decimal separator is specified as part of the document specification, then I'd go precisely as Steven does in using
CultureInfo.InvariantCulture
.If it's human input in a particular locale, then you would want to match that locale by the
CultureInfo
appropriate for that locale, otherwise if the software is used with a different locale you'd have precisely the opposite problem. Generally you would want to set the thread'sCurrentCulture
to match this (CurrentCulture
for formats,CurrentUICulture
for languages). If you've done this, then you don't need to pass a culture at all, as the formfloat.Parse(string)
uses that culture - however, you may wish to usefloat.Parse(string, CurrentCulture)
to be explicit that this is what you are doing (and to shut up some software analysis that complains when you aren't specific in this way).What gets really tricky, is if you potentially have to accept both period and comma - not least because many cultures that use period as a decimal separator, use comma as a thousands separator, and ultimately it's impossible to guarantee unambiguous parsing. However, assuming the thousands issue doesn't affect you, then the code you gave in your question is the approach, though I'd recommend doing the opposite (replace comma with period) and then parsing with the invariant culture, as that removes any further complications caused by yet more culture changes.
It depends on current culture of currently executed thread culture.
IF you strictly do not want culturespecific then
Using string replace is very fragile, and will lead to suttle bugs. Specify the
IFormatProvider
instead. For instance:Or you can specify the
NumberFormatInfo
using another overload ofParse
.