Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

When I try to convert a string to float:

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

it throws an exception:

Unhandled Exception: System.FormatException: Input string was not in a correct f ormat.
at System.Number.ParseSingle(String value, NumberStyles options, NumberFormat Info numfmt)

When I try it like this:

Console.WriteLine(Convert.ToSingle("6.59"));

It throws the same exception:

Unhandled Exception: System.FormatException: Input string was not in a correct f ormat.
at System.Number.ParseSingle(String value, NumberStyles options, NumberFormat Info numfmt)
at System.Convert.ToSingle(String value)

Can you explain why this happens?

like image 663
Edward83 Avatar asked Apr 08 '11 09:04

Edward83


People also ask

What is FormatException?

A FormatException exception can be thrown for one of the following reasons: In a call to a method that converts a string to some other data type, the string doesn't conform to the required pattern. This typically occurs when calling some methods of the Convert class and the Parse and ParseExact methods of some types.

How does Format handle exception?

To correct the error, either remove the format string or substitute a valid one. The following example corrects the error by replacing the invalid format string with the "C" (currency) format string. using System; public class Example { public static void Main() { decimal price = 169.32m; Console.


1 Answers

The single argument Parse method uses the current culture to parse the string. If your current culture uses some other decimal separator, this will fail.

Try using the invariant culture:

float.Parse("6.59", CultureInfo.InvariantCulture)
like image 179
R. Martinho Fernandes Avatar answered Oct 19 '22 01:10

R. Martinho Fernandes