How to convert float to String in Java

Facebooktwitterredditpinterestlinkedinmailby feather

How to convert float to String in java

There are following methods to convert float to String:

  • Convert using Float.toString(float)
  • Convert using String.valueOf(float)

Convert using Float.toString(float)

The Float class has a static method that returns a String object representing the specified float parameter. It returns the string representation of the float argument. The minus sign will be preserved if the number is negative. This is the most common method for converting the float value to String. The signature of this method is-

Where f represents the float value that we want to convert.

This method works similar to the String.valueOf(float) method except that it belongs to the Float class.

Example

In the following example, var is a variable of type float having value -7.22. str is a variable of type String that stores the value of var after conversion. Float is a wrapper class. toString() is a method of String class having var as an argument and returns the String representation of float value. The println statement prints the converted value of var.

Output

Convert using String.valueOf(float)

It is an overloaded method of String class under the java.lang package. You can pass the float value to this method as an argument. It returns the string representation of it. The signature of this method is-

Where f represents the float value that we want to convert.

Example

In the following example, val is a variable of type float having value 21.20. str is a variable of type String that stores the value of val after conversion. String is a class. valueOf() is a method of String class having val as an argument and returns the String representation of float value. The println statement prints the converted value of val.

Output

Facebooktwitterredditpinterestlinkedinmailby feather