It could be down to your system's culture which may be set to using a ,
as the separator. Setting the format to InvariantCulture
will use a .
for the separator.
Convert.ToSingle("12.123", CultureInfo.InvariantCulture)
Domanda
I have several strings
that I need to convert to float
. When I try to do so, using System.Convert.ToSingle(MyString)
, I always get a FormatException
.
I have tried even creating strings like "12.123"
, to make sure the numbers are okay, but again I got the exception. My question is, what is the correct format then? In what format should the number in string be?
Example of one of many strings I will convert: 50.105128
Soluzione
It could be down to your system's culture which may be set to using a ,
as the separator. Setting the format to InvariantCulture
will use a .
for the separator.
Convert.ToSingle("12.123", CultureInfo.InvariantCulture)
Altri suggerimenti
It depends on culture, but you can use invariant in this way:
Convert.ToSingle("0", System.Globalization.CultureInfo.InvariantCulture);
Convert.ToSingle is culture-sensitive. In culture installed on your machine, decimal separator might be different from comma, and number may look like 50,105128
Use this overload instead, which allows to specify culture:
public static float ToSingle(
Object value,
IFormatProvider provider
)