Home »
C# Tutorial
How to read float values in C#?
In this tutorial, we will learn how to read float value as an input in C# using various methods.
By IncludeHelp Last updated : April 06, 2023
Input float values in C#
The task is to take an input of a float value and print it on the console in C#.
As, we have discussed in earlier programs that to read any value, we use Console.ReadLine() method and if the desired value is not in the string format, we need to convert it into the specific type.
Different ways to read float inputs in C#
There are multiple ways to read float inputs in C#. The common ways to read float inputs are:
- Using float.Parse() Method
- Using Single.Parse() Method
- Using Convert.ToSingle() Method
1) Using float.Parse() Method
Here, float is an alias of Single class and Parse() is its method – it converts given string value to the float value.
Syntax
float_value = float.Parse(Console.ReadLine());
2) Using Single.Parse() Method
Single is a class and Parse() its method – it converts a string value to the float value.
Syntax
float_value = Convert.ToSingle(Console.ReadLine());
3) Using Convert.ToSingle() Method
Convert.ToSingle() method – Here, ToSingle() is a method of Convert class – it converts given object into the float value.
Syntax
float_value = Single.Parse(Console.ReadLine());
Example: Read float inputs using multiple methods in C#
In the below example, we have a variable value of "float" type, we are taking input from the user three times, and converting the value using all of the above-mentioned methods.
Note: float.Parse() and Single.Parse() both are similar, because float is an alias of Single class.
using System;
using System.Text;
namespace Test {
class Program {
static void Main(string[] args) {
//declaring a float variables and assigning it with
//a default value
float value = 0.0f;
//prompt message to take input
//using float.Parse()
Console.Write("Enter a float value: ");
value = float.Parse(Console.ReadLine());
//printing the value
Console.WriteLine("value = {0}", value);
//prompt message to take input
//using Single.Parse()
Console.Write("Enter a float value: ");
//resetting the value
value = 0.0f;
value = Single.Parse(Console.ReadLine());
//printing the value
Console.WriteLine("value = {0}", value);
//prompt message to take input
//using Convert.ToSingle()
Console.Write("Enter a float value: ");
//resetting the value
value = 0.0f;
value = Convert.ToSingle(Console.ReadLine());
//printing the value
Console.WriteLine("value = {0}", value);
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
Enter a float value: 123.456
value = 123.456
Enter a float value: 456.789
value = 456.789
Enter a float value: 012.45
value = 12.45