Different Ways to Take Input and Print a Float Value in C#In this article, we will discuss the different ways to take input and print a float value in C# with different methods. We are aware that Console.ReadLine() function can be used for reading the string to the output device. If the value is not of the string type by default, it is changed to the float type. There are several techniques for converting a given input to a float value. The below are the approaches which can be used are:
1. Parse() MethodThe Single.Parse() function is used for converting a string value to a float datatype value. This approach includes the following steps:
Syntax:The syntax can be defined as follows: Example:Let us take an example of the float value using the Single.Parse() method in C#. Filename: SingleParse.cs Input: Output: Value = 14.9 Explanation: In this example, the code first declared the float variable, initialized to 0.0, and the user is then prompted for input. The user input is collected as a string by the Console.ReadLine() function and is subsequently transformed into a float by Single.Parse(). Finally, Console.WriteLine() is used to display the parsed float values on the console. 2. Parse() MethodA built-in C# function called parseFloat() in the Float Class returns a new float that is initialized to its value, which is represented by the provided String. It is accomplished by the valueOf method of the Float class.
Syntax:It has the following syntax: Example:Let us take an example of using float to input a floating-point value using the float.Parse() Method in C#. Filename: FloatParse.cs Input: Output: Value = 45.9 Explanation: Variable Declaration:
Displaying the Value:
3. ToSingle() MethodThis method can be used for converting the number to it's corresponding single-precision floating-point number using the provided specific culture structuring information. Syntax:It has the following syntax: Parameters:val: A string containing the integer to be converted. provider: It is an object that provides formatting information for different cultures. Return Value: If val is null, this function returns a single-precision floating-point numbers integer that is comparable to the number in value or 0 (zero). Exceptions:
Example:The code samples below explain how to use Convert.ToSingle(String, IFormatProvider) method: Filename: ConvertToSingle.cs Input: Output: Value = 32.4 Explanation:
Next Topicfile.setLastAccessTime() Method in C# |