Wednesday, August 15, 2018

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, UI form can have input text value which accepts the floating value, To deal with form submission and do manipulation of this float values, We have to do the conversion 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 or F to decimal value to treat as float value String is a sequence of characters enclosed in double quotes with 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, Float class has a static method - public static String toString(float f) which accepts float primitive type 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 empty method We have to write a code like below
Float f1 =4.85f ;
System.out.println(f1.toString()); //outputs 4.85

Using String valueOf() method

The string has valueOf() has 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 Float class takes a string as value and convert 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);  
System.out.println(f);  
String s1="45abc.5";  
float f1=Float.parseFloat(s1);  
System.out.println(f);  
Output is
45.5
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)
Please like or share it in facebook/twitter.

Related article


EmoticonEmoticon