String to float conversion in Java – 3 ways

In this article, we will discuss various ways to convert String to float (or Float) in Java

 

What is the need of converting String to primitive float or Float wrapper-type ?

  • Generally, whenever we receive any data from web application then it all passed in the form of String only
  • To perform any mathematical operations on numbers which are received as String, need to be converted into respective type for further calculation
  • This article explains about String to primitive float or Float type conversion only, but we can do conversion for other types like long, double, int, etc
  • Note: Likewise, sometimes Float to String conversion is also required

 

Various ways to convert String to float (or Float)

  1. using Float.parseFloat(“strValue”);
  2. using Float.valueOf(“strValue”);
  3. Create Float object and then invoke floatValue() method {i.e.; new Float(“strValue”).floatValue();}

 

Exception scenario:

  • handle exception properly in all 3 ways
  • otherwise NumberFormatException will be thrown for incorrect string values (or not correctly formatted string)
  • and terminates program abruptly
  • we will see 3 different examples for all cases with E.1, E.2 and E.3

 

Auto-boxing and un-boxing feature from Java 1.5 version:

  • parseFloat() method returns primitive float type but it can be easily used as Float wrapper-type
  • as auto-boxing feature helps to convert primitive type to wrapper types
  • similarly, Float.valueOf() method returns Float wrapper type but it can also be used as primitive float data-type
  • let’s see one example on this auto-boxing feature at the very end

Read String class in detail with example

 

Let us move forward and discuss all possible ways to convert String to Float in Java

Way 1: Using Float.parseFloat(“strValue”); method

  • This method can be used to convert String which constitutes of floating numbers (or digits) into primitive float data-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.1 example

Method signature:

public static float parseFloat(String s) 
		throws NumberFormatException;

 

ConvertStringIntoFloatUsingParseFloatMethod.java

package in.bench.resources.string.to.floating.conversion;

public class ConvertStringIntoFloatUsingParseFloatMethod {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "123.45";

		// 1. converting String to float
		float fValue1 = Float.parseFloat(str1);
		System.out.println("1. Converted foat value is : "
				+ fValue1);


		// String with floating numbers/digits and minus sign (-)
		String str2 = "-123.45";

		// 2. converting String to float
		float fValue2 = Float.parseFloat(str2);
		System.out.println("\n2. Converted float value is : "
				+ fValue2);
	}
}

Output:

1. Converted foat value is : 123.45

2. Converted float value is : -123.45

 

Way 2: Using Float.valueOf(“strValue”); method

  • This method can be used to convert String which constitutes of only numbers (or digits) into Float wrapper-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.2 example

Method signature:

public static Float valueOf(String s) 
		throws NumberFormatException;

 

ConvertStringIntoFloatUsingValueOfMethod.java

package in.bench.resources.string.to.floating.conversion;

public class ConvertStringIntoFloatUsingValueOfMethod {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "98.765";

		// 1. converting String to Float
		Float fValue1 = Float.valueOf(str1);
		System.out.println("1. Converted Float value is : "
				+ fValue1);


		// String with floating numbers/digits and minus sign (-)
		String str2 = "-98.765";

		// 2. converting String to Float
		Float fValue2 = Float.valueOf(str2);
		System.out.println("\n2. Converted Float value is : "
				+ fValue2);
	}
}

Output:

1. Converted Float value is : 98.765

2. Converted Float value is : -98.765

 

Way 3: Create Float object and then invoke floatValue() method

  • Here, we will create new Float object with String as constructor-argument
  • After creating new Float object by passing string value, then invoke floatValue() method for converting String to primitive float data-type
  • Passed string to constructor-argument should constitutes of floating numbers (or digits)
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.3 example

Method signature:

public Float(String s) throws NumberFormatException;

public float floatValue();

 

ConvertStringIntoFloatUsingFloatValueMethod.java

package in.bench.resources.string.to.floating.conversion;

public class ConvertStringIntoFloatUsingFloatValueMethod {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "5.4545";

		// 1. converting String to float 
		// by creating new Float Object
		Float float1 = new Float(str1);
		float fValue1 = float1.floatValue();
		System.out.println("1. Converted float value is : "
				+ fValue1);


		// String with floating number/digits and minus sign (-)
		String str2 = "-5.4545";

		// 2. converting String to float 
		// by creating new Float Object
		Float float2 = new Float(str2);
		float fValue2 = float2.floatValue();
		System.out.println("\n2. Converted float value is : "
				+ fValue2);
	}
}

Output:

1. Converted float value is : 5.4545

2. Converted float value is : -5.4545

 

 

Exception scenarios:

  • In all above 3 cases, whenever string isn’t properly formatted to convert String to Float, then NumberFormatException will be thrown
  • We will see, what happens if string isn’t correctly formatted for all 3 ways of conversion

 

Case E.1: Handle NumberFormatException while converting String to float using Float.parseFloat() method

ParseFloatMethodThrowsNFE.java

package in.bench.resources.string.to.floating.conversion;

public class ParseFloatMethodThrowsNFE {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "12.3ben";

		// 1. converting String to float
		float fValue1 = Float.parseFloat(str1);
		System.out.println("1. Converted float value is : "
				+ fValue1);


		// String with floating number/digits and minus sign (-)
		String str2 = "-12.3ben";

		// 2. converting String to float
		float fValue2 = Float.parseFloat(str2);
		System.out.println("\n2. Converted float value is : "
				+ fValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: 
	For input string: "12.3ben"
	at sun.misc.FloatingDecimal.readJavaFormatString(
			FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(
			FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at in.bench.resources.string.to.floating.conversion
	.ParseFloatMethodThrowsNFE
	.main(ParseFloatMethodThrowsNFE.java:11)

 

Case E.2: Handle NumberFormatException while converting String to float using Float.valueOf() method

FloatValueOfMethodThrowsNFE.java

package in.bench.resources.string.to.floating.conversion;

public class FloatValueOfMethodThrowsNFE {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "54.5ben";

		// 1. converting String to float 
		// by creating new Float Object
		Float float1 = new Float(str1);
		float fValue1 = float1.floatValue();
		System.out.println("1. Converted float value is : "
				+ fValue1);


		// String with floating number/digits and minus sign (-)
		String str2 = "-54.5ben";

		// 2. converting String to float 
		// by creating new Float Object
		Float float2 = new Float(str2);
		float fValue2 = float2.floatValue();
		System.out.println("\n2. Converted float value is : "
				+ fValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: 
	For input string: "54.5ben"
	at sun.misc.FloatingDecimal.readJavaFormatString(
			FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(
			FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at java.lang.Float.<init>(Float.java:532)
	at in.bench.resources.string.to.floating.conversion
	.FloatValueOfMethodThrowsNFE
	.main(FloatValueOfMethodThrowsNFE.java:11)

 

Case E.3: Handle NumberFormatException while converting String to float using floatValue() method

FloatValueMethodThrowsNFE.java

package in.bench.resources.string.to.floating.conversion;

public class FloatValueMethodThrowsNFE {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "98.7ben";

		// 1. converting String to float 
		// by creating new Float Object
		Float float1 = new Float(str1);
		float fValue1 = float1.floatValue();
		System.out.println("1. Converted float value is : "
				+ fValue1);


		// String with floating number/digits and minus sign (-)
		String str2 = "-98.7ben";

		// 2. converting String to float 
		// by creating new Float Object
		Float float2 = new Float(str2);
		float fValue2 = float2.floatValue();
		System.out.println("\n2. Converted float value is : "
				+ fValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: 
	For input string: "98.7ben"
	at sun.misc.FloatingDecimal.readJavaFormatString(
			FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(
			FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at java.lang.Float.<init>(Float.java:532)
	at in.bench.resources.string.to.floating.conversion
	.FloatValueMethodThrowsNFE
	.main(FloatValueMethodThrowsNFE.java:11)

 

What if we want to convert primitive float data-type to Float wrapper-type or vice-versa ?

  • Auto-boxing feature available from Java 1.5 version
  • So, converting primitive data-type to wrapper-type can easily be done, by directly assigning
  • Let’s see one example based on this auto-boxing feature

AutoBoxingFeatureForFloatConversion.java

package in.bench.resources.string.to.floating.conversion;

public class AutoBoxingFeatureForFloatConversion {

	public static void main(String[] args) {

		// String with floating numbers or digits
		String str1 = "12.345";

		// string to float conversion
		float fValue1 = Float.parseFloat(str1);

		// 1. Auto-Boxing - converting float to Float
		Float fAutoBoxing = fValue1;
		System.out.println("1. Auto-Boxing : " 
				+ fAutoBoxing);

		// String with floating number/digits and minus sign (-)
		String str2 = "-98.765";

		// string to Float conversion
		Float fValue2 = Float.valueOf(str2);

		// 2. Un-Boxing - converting Float to float
		float fUnBoxing = fValue2;
		System.out.println("\n2. Un-Boxing   : " 
				+ fUnBoxing);
	}
}

Output:

1. Auto-Boxing : 12.345

2. Un-Boxing   : -98.765

 

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

References:

 

Happy Coding !!
Happy Learning !!

Float to String conversion in Java - 6 ways
Integer to String conversion in Java - 6 ways