Convert float to String and String to float in Java

JavaStringTypesNumber FormattingType Conversion

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 - Java

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 - Java

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 - Java

I believe the following code will help:

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

Solution 5 - Java

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 {

/**
 * <p>This method is to  main</p>
 * @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

Solution 6 - Java

If you're looking for, say two decimal places.. Float f = (float)12.34; String s = new DecimalFormat ("#.00").format (f);

Solution 7 - Java

well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use,

float val=10.0;
String str=val+"";

the empty quotes, add a null string to the variable str, upcasting 'val' to the string type.

Solution 8 - Java

String str = "1234.56";
float num = 0.0f;

int digits = str.length()- str.indexOf('.') - 1;

float factor = 1f;

for(int i=0;i<digits;i++) factor /= 10;

for(int i=str.length()-1;i>=0;i--){

    if(str.charAt(i) == '.'){
        factor = 1;
        System.out.println("Reset, value="+num);
        continue;
    }

    num += (str.charAt(i) - '0') * factor;
    factor *= 10;
}

System.out.println(num);

Solution 9 - Java

There are three ways to convert float to String.

  1. "" + f
  2. Float.toString(f)
  3. String.valueOf(f)

There are two ways Convert String to float

  1. Float.valueOf(str)
  2. Float.parseFloat(str);

Example:-

public class Test {

	public static void main(String[] args) {
		System.out.println("convert FloatToString " + convertFloatToString(34.0f));

		System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));

		System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));
		
		float f = Float.valueOf("23.00");
	}

	public static String convertFloatToString(float f) {
		return "" + f;
	}

	public static String convertFloatToStrUsingFloatMethod(float f) {
		return Float.toString(f);
	}

	public static String convertFloatToStrUsingStringMethod(float f) {
		return String.valueOf(f);
	}
	
}

Solution 10 - Java

To go the full manual route: This method converts doubles to strings by shifting the number's decimal point around and using floor (to long) and modulus to extract the digits. Also, it uses counting by base division to figure out the place where the decimal point belongs. It can also "delete" higher parts of the number once it reaches the places after the decimal point, to avoid losing precision with ultra-large doubles. See commented code at the end. In my testing, it is never less precise than the Java float representations themselves, when they actually show these imprecise lower decimal places.

/**
 * Convert the given double to a full string representation, i.e. no scientific notation
 * and always twelve digits after the decimal point.
 * @param d The double to be converted
 * @return A full string representation
 */
public static String fullDoubleToString(final double d) {
	// treat 0 separately, it will cause problems on the below algorithm
	if (d == 0) {
		return "0.000000000000";
	}
	// find the number of digits above the decimal point
	double testD = Math.abs(d);
	int digitsBeforePoint = 0;
	while (testD >= 1) {
		// doesn't matter that this loses precision on the lower end
		testD /= 10d;
		++digitsBeforePoint;
	}

	// create the decimal digits
	StringBuilder repr = new StringBuilder();
	// 10^ exponent to determine divisor and current decimal place
	int digitIndex = digitsBeforePoint;
	double dabs = Math.abs(d);
	while (digitIndex > 0) {
		// Recieves digit at current power of ten (= place in decimal number)
		long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
		repr.append(digit);
		--digitIndex;
	}

	// insert decimal point
	if (digitIndex == 0) {
		repr.append(".");
	}

	// remove any parts above the decimal point, they create accuracy problems
	long digit = 0;
	dabs -= (long)Math.floor(dabs);
	// Because of inaccuracy, move to entirely new system of computing digits after decimal place.
	while (digitIndex > -12) {
		// Shift decimal point one step to the right
		dabs *= 10d;
		final var oldDigit = digit;
		digit = (long)Math.floor(dabs) % 10;
		repr.append(digit);

		// This may avoid float inaccuracy at the very last decimal places.
		// However, in practice, inaccuracy is still as high as even Java itself reports.
		// dabs -= oldDigit * 10l;
		--digitIndex;
	}

	return repr.insert(0, d < 0 ? "-" : "").toString();	
}

Note that while StringBuilder is used for speed, this method can easily be rewritten to use arrays and therefore also work in other languages.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlolaView Question on Stackoverflow
Solution 1 - JavaPetar IvanovView Answer on Stackoverflow
Solution 2 - JavaKV PrajapatiView Answer on Stackoverflow
Solution 3 - JavaJMaxView Answer on Stackoverflow
Solution 4 - Javaomt66View Answer on Stackoverflow
Solution 5 - JavaAnupamView Answer on Stackoverflow
Solution 6 - JavaRichEarleView Answer on Stackoverflow
Solution 7 - JavaAnmol ThukralView Answer on Stackoverflow
Solution 8 - JavagpaView Answer on Stackoverflow
Solution 9 - JavaNeeraj GahlawatView Answer on Stackoverflow
Solution 10 - Javakleines FilmröllchenView Answer on Stackoverflow