开发者

Parse string to float number C#

I have float number in string. there is one problem. Number uses "." not "," as decimal point.

This code is not working:

MyNumber = float.Parse("1开发者_如何学运维23.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?


Using string replace is very fragile, and will lead to suttle bugs. Specify the IFormatProvider instead. For instance:

MyNumber = float.Parse("123.5", CultureInfo.InvariantCulture);

Or you can specify the NumberFormatInfo using another overload of Parse.


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's CurrentCulture 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 form float.Parse(string) uses that culture - however, you may wish to use float.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.

float.Parse("123,5", system.threading.thread.currentthread.currentculture); 

float.Parse("123.5", system.threading.thread.currentthread.currentculture); 

IF you strictly do not want culturespecific then

float.Parse("123.5", CultureInfo.InvariantCulture);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜