简体   繁体   中英

How do i convert to different datatypes in C#

I am new to C# and am trying some things in a console application. I am trying to get the userinput and convert it to the different datatypes and then display the converted data.

I tried this so far:

string  userInput;
int     intInput;
float   floatInput;

Console.WriteLine("Please enter a number: ");
userInput = Console.ReadLine();

intInput = Convert.ToInt32(userInput);
floatInput = (float)intInput;


Console.WriteLine("String input: "+userInput+"\n");
Console.WriteLine("Integer input: " + intInput + "\n");
Console.WriteLine("Float input: " + floatInput + "\n");

It doesn't give me any errors in visual studios, but when i run the program it likes integer numbers and displays them. But when I input a number like 4.4 it stops the program with a warning FormatException was unhandled for this line inInput = convert.ToInt32(userInput); .

My locals window shows:

userInput = "4.4"
intInput = 4
floatInput = 4.0

Why am I getting this error? Is this the correct way to convert datatypes?

edit: because I don't know what the user might input how can I test it somehow?

Error

You are getting this error because "4.4" is not a value that represents an Integer, hence it cannot be converted.

The following is a great article for gaining a better understanding of the basic data types and typical values:

http://www.tutorialspoint.com/csharp/csharp_data_types.htm

Converting

Be aware that there are a few ways to handle the task you've set out to achieve here of 'converting' a string to another data type.

For Integers, for example, you could use TryParse:

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

TryParse would not raise an exception and break your app as this has.

Handling Exceptions

Also note, 'unhandled' here means that your code does not handle this kind of error, which it could have - with appropriate Try Catch blocks:

http://msdn.microsoft.com/en-us/library/vstudio/0yd65esw.aspx

Wrapping potentially erroneous code with Try Catch blocks allows you to handle an exception more gracefully.

4.4 is not an integer, it's (perhaps) a decimal.

If you'd like to accept decimal input, you'll need to change your variable's type, and then use Convert.ToDecimal instead.

datatype test="xyz"; // datatype- int, float..

datatype.TryParse(variable, out test);

if(test=="xyz") //parsing can be done

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM