M.hjespersen M.hjespersen - 2 months ago 7
C# Question

How can I solve "Input string was not in correct format"

Its one of my first projekts, and its even copied off a Danish beginner book, I have double checked serval times, and they're identical, but there still seems to be an error.

using System;

namespace Amount_and_price
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Write the price here ");
String text = Console.ReadLine();
double price = Convert.ToDouble(text);
Console.WriteLine("Write the amount here ");
text = Console.ReadLine();
int quantity = Convert.ToInt32(text);
double amount = price * quantity;
double vat = amount * 0.25;
double total = amount + vat;
Console.WriteLine("{0, -15} { 1, 10:F}", "Pris på varen", price);
Console.WriteLine("{0, -15} { 1, 10:D}", "Antal styk", quantity);
Console.WriteLine("{0, -15} { 1, 10:F}", "Pris eks. moms", amount);
Console.WriteLine("{0, -15} { 1, 10:F}", "Moms", vat);
Console.WriteLine("{0 -15} { 1, 10:F}", "Total pris, inkl. moms", total);

}
}
}


What do I need to change so the error "Input string was not in correct format" doesn't appear?

Answer

You cannot have spaces between the opening brace and the argument number in your Console.WriteLine statement. All your Console.WriteLine statements need to be modified with this change. Below is an illustrative line to explain the change

Wrong Code

Console.WriteLine("{0, -15} { 1, 10:F}", "Pris på varen", price);

Right Code

Console.WriteLine("{0,-15} {1,10:F}", "Pris på varen", price);

Also your last Console.WriteLine statement has a missing comma (as pointed out by @Berkay

Wrong Code

Console.WriteLine("{0  -15} {1, 10:F}", "Total pris, inkl. moms", total);

Right code

Console.WriteLine("{0,-15} {1,10:F}", "Total pris, inkl. moms", total);