How to convert String to float in Java

A floating-point data type is a group of data types that behave similarly and differ mainly in their domain sizes (the allowable values). Number values having fractional portions are represented via the floating-point family of data types. A mantissa and an exponent are the two integer values that they are stored as. In all programming languages, the floating-point family has the same attributes and acts or behaves in the same way. They can always hold negative or positive numbers, hence they are always signed, as opposed to the integer data type, which can be unsigned. Floating-point data types have a wide range of domains because they may represent extremely big or very tiny values. The bigger the mantissa and exponent, and hence the more accuracy, the more bytes of storage. So let us start on the tutorial of How to convert String to float in Java.

 

What’s The Approach?

 

  • Import the java. util package into the class.

 

  • Now within the main method create a new object of Scanner class, for example, Scanner sc=new Scanner(System. in);

 

  • Use the Scanner class to get the input from the user.

 

  • Use the try and catch to prevent unwanted errors from the user.

 

  • Apply the Float.parseFloat(String_Name); to convert the string to float type

 

Also Read: How to Reverse a Number in Java using for loop

 

Java Program to convert String to Float in Java

/*
 * TechDecode Tutorials
 * 
 * How to Covert String to Float
 * 
 */

import java.util.*;
public class String_to_Float
{
    public static void main(String args[])
    {
        // Creating an object of Scanner class
        Scanner sc=new Scanner (System.in);
        // taking imput from  the user
        System.out.print("Please Enter the String that is to be converted to Float: ");
        String s=sc.nextLine();
        //using try and catch to prevent Wrong inputs
        try
        {
            // converting string to Float
            float num=  Float.parseFloat(s);
            //Printing the Float value
            System.out.println("The converted String to Float is: "+ num);
        }
        catch (NumberFormatException ex){
            //Displaying message for wrong input
            System.out.println("Sorry Wrong Input");

        }
    }
}

Input:- 45.123

Output:-

Leave a Reply

Your email address will not be published. Required fields are marked *