Signup/Sign In
LAST UPDATED: SEPTEMBER 1, 2020

Java Float toString(float f) Method

Java toString() method is a part of the Float class of the java.lang package. This method returns the equivalent String object of the float value passed as an argument.

In short, this method is used to convert float value into String.

Syntax:

public static String toString(float f)

Parameter:

The parameter passed is the float value whose equivalent String is to be returned.

Returns:

Returns the String equivalent of the float value passed as a parameter. It must be noted that String "NaN" is returned for the float value, NaN.

Example 1:

Here, the float values are converted into its equivalent String representations.

import java.lang.Float;

public class StudyTonight
{  
    public static void main(String[] args)
    {  
        float a = 40.95f;
        float b = -56.27f;
        System.out.println("Equivalent String is : " + Float.toString(a));   
        System.out.println("Equivalent String is : " + Float.toString(b));   
    }  
} 


Equivalent String is : 40.95
Equivalent String is : -56.27

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner;  

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        try
        {
            System.out.print("Enter the value ");  
            Scanner sc = new Scanner(System.in);  
            float val = sc.nextFloat();  
            String s = Float.toString(val); //converting to string
            System.out.println("String value is : "+ s);  
        }
        catch(Exception e)
        {
            System.out.println("Invalid input!!");
        }
    }  
}


Enter the value NaN
String value is : NaN
*************************
Enter the value 90.476
String value is : 90.476
**************************
Enter the value 0x590
Invalid input!!

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.