Why do I get a FormatException when converting a string to a float?

后端 未结 7 1502
傲寒
傲寒 2021-02-19 06:46

When I try to convert a string to float:

Console.WriteLine(float.Parse(\"6.59\"));

it throws an exception:

Unhandled Exc

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 07:13

    The problem here is your culture.

    Either set the invariant culture like this:

    float.Parse("6.59", CultureInfo.InvariantCulture)
    

    or use the correct decimal separator for your culture

    float.Parse("6,59")
    

    I wonder why you are using a literal string. If you are having problems entering literal floats, you can use

    Console.WriteLine(6.59f)
    

    If you do it this way culture doesn't matter because the value is decided at compile time.

提交回复
热议问题