This tutorial explains how to convert variable types in the C# language (eg. convert from string to integer or float, or convert from integer or float to string). Here is a summary of the methods used:
- float.Parse() – converts to float type
- int.Parse() – converts to int type
- .ToString() – converts to string type
Watch the video below and then scroll down to see the sample code.
Example of converting from string to float:
float myFloatVariable = float.Parse(myStringVariable);
Example of converting from string to int:
int myIntVariable = int.Parse(myStringVariable);
Example of converting from int or float to string:
string myStringVariable = myFloatVariable.ToString();
Here is the full sample code from the tutorial video:
using System; namespace MyCSharpProject { class MainClass { public static void Main(string[] args) { Console.WriteLine("Enter your name: "); string username = Console.ReadLine(); // store user input as string Console.WriteLine("Hello there, " + username); Console.WriteLine("Enter two numbers"); float num1 = float.Parse(Console.ReadLine()); // convert user input from string to float float num2 = float.Parse(Console.ReadLine()); // convert user input from string to float Console.WriteLine("The result is: " + (num1 + num2)); // display string of text and float result int num3 = 5; int num4 = 10; Console.WriteLine(num3.ToString() + num4.ToString()); // convert int to string } } }
Next tutorial: Making comparisons in C#