The undertaking is to make a contribution of a float worth and print it on the support in C#.
As we have examined in before programs that to peruse any worth, we use Console.ReadLine() method and if the ideal worth isn’t in the string design, we have to convert it into the particular kind.
There is a portion of the normal and famous approaches to convert an incentive to the float,
float.Parse() method – Here, the float is a pseudonym of Single class and Parse() is its method – it converts given string an incentive to the float esteem.
Language structure:
float_value = float.Parse(Console.ReadLine());
Single.Parse() method – Single is a class and Parse() its method – it converts a string an incentive to the float esteem.
Grammar:
float_value = Single.Parse(Console.ReadLine());
Convert.ToSingle() method – Here, ToSingle() is a method of Convert class – it converts given article into the float esteem.
Language structure:
float_value = Convert.ToSingle(Console.ReadLine());
Model:
In the beneath model, we have a variable estimation of “float” type, we are taking a contribution from the client multiple times, and converting the worth utilizing the entirety of the previously mentioned methods.
Note: float.Parse() and Single.Parse() both are comparative since float is a moniker of Single class.
C# code to read a float value and print it on the console
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