How to declare double as a variable with Console.Readline() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to declare double as a variable with Console.Readline()

Hello. My question is how to declare a variable in double format.I am trying System.Convert.ToDouble but i have error "Input string was not in a correct format"... My Code: double a = System.Convert.ToDouble(Console.ReadLine());

1st Jun 2020, 4:19 PM
Matthew
Matthew - avatar
6 Answers
1st Jun 2020, 4:39 PM
Matthew Shoop
Matthew Shoop - avatar
+ 2
Matthew Having read your previous reply, probably your computer system was setup with a locale which uses comma ',' instead of a dot '.' for decimal separator. If this was the case, then follow the settings and use comma as decimal separator for giving input.
1st Jun 2020, 5:34 PM
Ipang
+ 1
If you want to add a bit of fault tolerance to the code, you can use `TryParse` instead. You get to check whether the given input was convertible to `double` type by that. // paste in main method double d; bool okay = Double.TryParse(Console.ReadLine(), out d); if(okay) // conversion success! { Console.WriteLine("The double value is {0}", d); } else // something's not right { Console.WriteLine("Your input is not okay."); }
1st Jun 2020, 4:46 PM
Ipang
0
What was your input string?
1st Jun 2020, 4:31 PM
Matthew Shoop
Matthew Shoop - avatar
0
"3.12" for example
1st Jun 2020, 4:32 PM
Matthew
Matthew - avatar
0
I use Visual studio and if i put 3.12 its error but if i use comma 3,12 its ok... It is fine or what?
1st Jun 2020, 4:42 PM
Matthew
Matthew - avatar