Stefan
Stefan

Reputation: 1

Console readline fractional number

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."

Upvotes: -1

Views: 62

Answers (1)

Neil
Neil

Reputation: 11889

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

Upvotes: 0

Related Questions