java : convert float to String and String to float

lola picture lola · Sep 26, 2011 · Viewed 847k times · Source

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

Answer

Petar Ivanov picture Petar Ivanov · Sep 26, 2011

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.)