How to Convert Float to String or String to Float in java with examples

Convert Float to String or String to Float in java

Float and String are data types of objects used to store different values.

In Applications, the UI form can have an input text value that accepts the floating value, To deal with form submission and do manipulation of these float values. We do convert for String to float or float to String in Java. This tutorial talks about various ways to do this conversion.

float values example

float f = (float) 4.8;  
float f1 =8.56f;  
float f2 =5.67F;  

In java when you give decimal data - 8.59 value, it treats as double type, We have to add F to the decimal value to treat it as float value String is a sequence of characters enclosed in double-quotes with the single variable name.

How to convert Float to String in java with an example?

We can convert Float to String in many ways.

using toString() method

For float primitive types, the Float class has a static method - public static String toString(float f) which accepts float primitive types have to write a code like below Example

float f =3.585f ;  
String s = Float.toString(f);  

For Float Object, Float object has to call toString() with the empty method. We have to write a code like the one below.

Float f1 =4.85f ;  
System.out.println(f1.toString()); //outputs 4.85  

Using String valueOf() method

The string has valueOf() has an overloaded static method which takes float value and returns the string value of a float data Example.

float f = 4.89F;  
String ss = String.valueOf(f);  
System.out.println(ss);  // outputs 4.89  

How to convert String to Float in java with an example?

This conversion can be done in many ways.

using Float.parseFloat() method

parseFloat() method in the Float class takes a string as a value and converts this string value to float. If the string is unable to convert it, NumberFormatException will be thrown.

String s="45.5";    
float f=Float.parseFloat(s);    
String s1="45abc.5";    
float f1=Float.parseFloat(s1);    

Output is

Exception in thread "main" java.lang.NumberFormatException: For input string: "45abc.5"  
 at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)  
 at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)  
 at java.base/java.lang.Float.parseFloat(Float.java:455)  
 at ArraysDemo.main(ArraysDemo.java:29)  
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.