Convert float to String and String to float in Java
Solution 1
Using Java’s Float
class.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
To compare it's always better to convert the string to float and compare as two floats. This is because for one float number there are multiple string representations, which are different when compared as strings (e.g. "25" != "25.0" != "25.00" etc.)
Solution 2
Float to string - String.valueOf()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float - Float.parseFloat()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)
Solution 3
You can try this sample of code:
public class StringToFloat
{
public static void main (String[] args)
{
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try
{
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
found here
Solution 4
I believe the following code will help:
float f1 = 1.23f;
String f1Str = Float.toString(f1);
float f2 = Float.parseFloat(f1Str);
Solution 5
If you're looking for, say two decimal places..
Float f = (float)12.34;
String s = new DecimalFormat ("#.00").format (f);
Related videos on Youtube
lola
Updated on April 20, 2022Comments
-
lola about 2 years
How could I convert from float to string or string to float?
In my case I need to make the assertion between 2 values string (value that I have got from table) and float value that I have calculated.
String valueFromTable = "25"; Float valueCalculated =25.0;
I tried from float to string:
String sSelectivityRate = String.valueOf(valueCalculated);
but the assertion fails
-
xtofl over 12 yearsyou are aware that
float
values are never precise? -
Vishy over 12 yearsDo you want to compare them as
String
or asfloat
values? This is not the same thing.float
is less precise thandouble
and either can have rounding errors from calculated values. -
Vishy over 12 yearsgoogle not to be confused with googol. ;)
-
lola over 12 yearsI tried you solution and also from goggle but when I make the assertion I got :java.lang.AssertionError: expected:<25> but was:<25.0>
-
-
Hein du Plessis over 11 yearsThanks - helped me, needed the catch bit ;)
-
Jonathan about 9 yearsDo i need to import something for this to work? I get undefied type 'Float' (I'm in a weird java environment though, openhab scripts)