Read value from console and convert it to float in CSharp

Description

The following code shows how to read value from console and convert it to float.

Example


using System;// www  .  j a va  2 s  . c o  m
using System.Globalization;

public class Example
{
    public static void Main()
    {

        bool done = false;
        string inp;
        do
        {
            Console.Write("Enter a real number: ");
            inp = Console.ReadLine();
            try
            {
                Single s = Single.Parse(inp);
                Console.WriteLine("You entered {0}.", s.ToString());
                done = true;
            }
            catch (FormatException)
            {
                Console.WriteLine("You did not enter a number.");
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception occurred while parsing your response: {0}", e.ToString());
            }
        } while (!done);

    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var