Console readline fractional number

50 Views Asked by At

Why with

double number = double.Parse(Console.ReadLine());
Console.WriteLine($"{number:0.00}");

or

double number = double.Parse(Console.ReadLine());
Console.WriteLine("{0:0.00}", number);

the console doesn't write the fractional number i have writen and says:

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

1

There are 1 best solutions below

2
Neil On

It works for me here's a dotnet fiddle: https://dotnetfiddle.net/f6FKd4

    string input = "1.234";
    
    double number = double.Parse(input);
    Console.WriteLine($"{number:0.00}");

output: 1.23

From the error message, it looks like what you are typing in (and parsing) as the input is the exception.

Same thing with a culture that uses comma and period differently:

    CultureInfo.CurrentCulture = new CultureInfo("nl-NL");
    string input = "1.234,56";
    
    double number = double.Parse(input);
    Console.WriteLine($"{number:0.00}");

output: 1234,56