Вопрос

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

Это было полезно?

Решение

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)

Другие советы

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
)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top