I'm trying to get a string formatted float number (e.g. "3.14") from a COM port.
I used Convert.ToSingle()
but it threw exception "Input string was not in a correct format" And while debugging, I found that double, float and decimal numbers are separated by '/' instead of '.'; for example 3.14 was 3/14.
My system language is English, but date and time formats are in Persian (Windows 10). In Persian, we use / instead of . as the decimal symbol.(۳/۱۴ = 3.14)
Is there any way to make program independent of system regional settings and force it to always use '.' as decimal symbol?
Using Convert.ToSingle
will attempt to convert an object to a floating-point number based on the system's region settings, as you have already noticed.
In order to reliably convert a string that is, for example, in US-English format, you can provide an additional argument of the type IFormatProvider
to the method.
string text = "3.5";
IFormatProvider culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
float number = Convert.ToSingle(text, culture);
The result stored in number
be 3.5
, i.e. the number halfway between three and four, independent of your system settings. For example, the above code works as expected on my computer, even though it's set to the German (de-DE) region, which represents the same number as 3,5
.
See also the documentation of Convert.ToSingle
for details.