Parse string to float number C#

2019-01-12 06:21发布

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?

3条回答
我命由我不由天
2楼-- · 2019-01-12 06:36

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.

查看更多
Luminary・发光体
3楼-- · 2019-01-12 06:45

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);
查看更多
放荡不羁爱自由
4楼-- · 2019-01-12 06:53

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.

查看更多
登录 后发表回答