-1

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

001
  • 13,291
  • 5
  • 35
  • 66
Stefan
  • 1
  • 5
    Are you using the correct decimal char? Based on your locale, it could be `.` or `,`. – 001 Jul 10 '23 at 18:50
  • 1
    What is the string value you get from `Console.ReadLine()`? Would be better for debugging to store the string in a variable before parsing. – D Stanley Jul 10 '23 at 18:51
  • try to use `try` and `catch` to see what's wrong. – Han Han Jul 10 '23 at 18:53
  • `double.Parse()` without a CultureInfo argument will use the user's ie yours, locale settings to parse the string. If you use the wrong decimal separator you'll get the error you posted. The dot is the decimal separator only in half the world and then only because China and Pacific countries use it too. The *rest* of the world uses `,` – Panagiotis Kanavos Jul 10 '23 at 19:07

1 Answers1

0

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

Neil
  • 11,059
  • 3
  • 31
  • 56
  • I bet the exact same input would cause the exception in the OP's machine, and more than half of the world. `Parse()` uses the user's locale settings and `.` is the decimal separator in China, Australia and other countries around the Pacific only. Origin omission intentional. If it wasn't for *China* I'd safely say "most of the world uses ,*" – Panagiotis Kanavos Jul 10 '23 at 19:09
  • Without knowing exactly what the input actually is, there's not much we can do but speculate. – Neil Jul 10 '23 at 19:25