Console.WriteLine("Enter a double number");
string numberInput = Console.ReadLine();
double number = Double.Parse(numberInput)
My question is what is the last line of code doing? Is it doing the same thing as ToDouble
?
The very short answer is:
Converts a string value into a double. eg
"2.3"(String) will become 2.3(double).
You have many choices on how to do this:
Double.TryParse() is handy if you don't know 100% that the input string is going to be a number value.
它将string
转换为double
, Console.ReadLine()
方法读取字符串数据并将其存储在名为numberInput
string
变量中,以将其从字符串转换为double
, Double.Parse
,我们将其传递给numberInput
字符串,会将其转换为两倍。
"Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent."
See MSDN .
It's taking String
input and interpreting it as numeric input - Double
in this case. String
and Double
are quite different types. For one, mathematical operations can be performed on Double
.
Converts the string representation of a number to its double-precision floating-point number equivalent.
MSDN: http://msdn.microsoft.com/en-us/library/system.double.parse.aspx
It's calling the Double.Parse method. According to the MSDN page it
Converts the string representation of a number to its double-precision floating-point number equivalent.
As per @DoctorMick's answer : It does the same thing as the Convert.ToDouble
method.
In this case it's used because the code is getting a string
from the user which can be thought of as a sequence of letters. We would want to get this into the proper type that we want to work with, which in this case is Double
. Double has the parse method for this.
The data read into the variable numberInput
is a string. The last line parses this into the type System.Double
, so that it is better typed for other operations.
There is no guarantee that numberInput
contains a valid numeric value, in which case the Parse method will throw an exception that you can catch.
There have been 7 different answers yet everyone seems to have overlooked the question of is it doing the same as ToDouble. The short answer is yet, it is doing the same, in fact ToDouble calls double.Parse internally.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.