Convert float to String and String to float in Java

885,924

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

Share:
885,924

Related videos on Youtube

lola
Author by

lola

Updated on April 20, 2022

Comments

  • lola
    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
      xtofl over 12 years
      you are aware that float values are never precise?
    • Vishy
      Vishy over 12 years
      Do you want to compare them as String or as float values? This is not the same thing. float is less precise than double and either can have rounding errors from calculated values.
    • Vishy
      Vishy over 12 years
      google not to be confused with googol. ;)
    • lola
      lola over 12 years
      I 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
    Hein du Plessis over 11 years
    Thanks - helped me, needed the catch bit ;)
  • Jonathan
    Jonathan about 9 years
    Do i need to import something for this to work? I get undefied type 'Float' (I'm in a weird java environment though, openhab scripts)