Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.FormatException: Input string was not in a correct format

    private void ReadUnitPrice()
    {
        Console.Write("Enter the unit gross price: ");
        unitPrice = double.Parse(Console.ReadLine());
    }

This should work, but I'm missing something obvious. Whenever I input a double it gives me the error: System.FormatException: Input string was not in a correct format. Note that 'unitPrice' is declared as a double.

like image 247
Petrus K. Avatar asked Sep 23 '11 17:09

Petrus K.


People also ask

How do I fix the input string was not in a correct format?

Input string was not in a correct format error occurs when you convert non-numeric data into an int or exceed the limit of the int data type. You should use Int. TryParse instead of Int32. Parse method to get rid of the said error.

What is an input string?

String input templates allow you to specify the type, order, and number of characters a user can enter in a data entry field. You can define string input templates only on single‑line character data entry fields.


1 Answers

It could be that you're using wrong comma separation symbol or even made an other error whilst specifying double value. Anyway in such cases you must use Double.TryParse() method which is safe in terms of exception and allows specify format provider, basically culture to be used.

public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out double result
)

The TryParse method is like the Parse(String, NumberStyles, IFormatProvider) method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero.

EDIT: Answer to comment

if(!double.TryParse(Console.ReadLine(), out unitPrice))
{
    // parse error
}else
{
   // all is ok, unitPrice contains valid double value
}

Also you can try:

double.TryParse(Console.ReadLine(), 
                NumberStyle.Float, 
                CultureInfo.CurrentCulture, 
                out unitPrice))
like image 118
sll Avatar answered Sep 22 '22 04:09

sll