Home > OS >  error when converting string value entered to double,is there the better way other than this?
error when converting string value entered to double,is there the better way other than this?

Time:07-21

using System;

namespace ConsoleApp1 { class program { public static void Main() { int qty; double price;

        Console.WriteLine("please enter the qty");
        qty = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("please enter the price ");
        price = Convert.ToDouble(Console.ReadLine());

        double total = price * qty;
        Console.WriteLine($"tota is : {total:c}");

        Console.ReadKey();  
    }
}

}

output

please enter the qty

3

please enter the price

12.44

error message after entering double: 12.44

Unhandled exception. System.FormatException: Input string was not in a correct format. at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Convert.ToDouble(String value) at ConsoleApp1.program.Main() in C:\Users\Baba\Desktop\C#\ConsoleApp1\ConsoleApp1\Program.cs:line 14

CodePudding user response:

Welcome to SO! In addition to @PaulSinnema 's input: you could try TryParse() to detect/ avoid invalid user input:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //int qty;
            //double price;

            Console.WriteLine("please enter the qty");
            //qty = Convert.ToInt32(Console.ReadLine());
            var input = Console.ReadLine();
            if (!Int32.TryParse(input, out int qty))
            {
                Console.WriteLine($"invalid input \"{input}\"");
                Console.ReadKey();
                return;
            }

            Console.WriteLine("please enter the price ");
            //price = Convert.ToDouble(input);
            input = Console.ReadLine();
            if (!double.TryParse(input, out double price))
            {
                Console.WriteLine($"invalid input \"{input}\"");
                Console.ReadKey();
                return;
            }

            double total = price * qty;
            Console.WriteLine($"total is : {total:c}");

            Console.ReadKey();
        }
    }
}

The Windows "Region" / "Customize Format" dialog

  • Related