'read user input of double type
I have found this answered in other places using loops, but I wasn't sure if there is actually a function that I'm not finding that makes this easier, or if this is a possible (in my opinion) negative side to C#.
I'm trying to read in a double from user input like this:
Console.WriteLine("Please input your total salary: ") // i input 100
double totalSalary = Console.Read(); //reads in the 1, changes to 49.
I've found a couple other posts on this, and they all have different answers, and the questions asked aren't exactly the same either. If i just want the user input read in, what is the best way to do that?
Solution 1:[1]
You'll have to check the entire thing on it's way in.. as Console.Read() returns an integer.
double totalSalary;
if (!double.TryParse(Console.ReadLine(), out totalSalary)) {
// .. error with input
}
// .. totalSalary is okay here.
Solution 2:[2]
Try this:
double Salary = Convert.ToDouble(Console.ReadLine());
Solution 3:[3]
Simplest answer to your question:
double insert_name = Double.Parse(Console.ReadLine());
Solution 4:[4]
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simon Whitehead |
| Solution 2 | chappjc |
| Solution 3 | Community |
| Solution 4 | John |
