Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java : convert float to String and String to float

People also ask

Can you convert a string to a float in Java?

We can convert String to float in java using Float. parseFloat() method.

Can we convert float to string?

The Float. toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.

What converts the string value into float?

In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.


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


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)

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


I believe the following code will help:

float f1 = 1.23f;
String f1Str = Float.toString(f1);      
float f2 = Float.parseFloat(f1Str);

This is a possible answer, this will also give the precise data, just need to change the decimal point in the required form.

public class TestStandAlone {

    /**
     * 

This method is to main

* @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Output will be

f1 --> 152.32
s1 152.32