Monday, 19 September 2016

Converting string to float - Java Program

There are several instances when you want to convert a string to float data type so in this post we’ll see what different ways do we have for this conversion.

In Java, Float class provides two methods for converting string to float -

  • parseFloat(String s) - Returns a new float initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable number.
  • valueOf(String s) - Returns a Float object holding the float value represented by the argument string s. Throws NumberFormatException if the string does not contain a parsable number.

Here Few things to note are -

  1. Both of the methods are static so you can use them directly with the class i.e. Float.parseFloat(String s) and Float.valueOf(String s).
  2. If you have noticed parseFloat method returns float (primitive data type) where as valueOf() method returns Float class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “f” or “F” (even d or D which denotes double) with the float value so having string as “56.78f” will not throw NumberFormatException while converting where as “56.78a” will throw exception.

Note that Float class also has a constructor that takes String as argument so that is also one way to convert string to float.

  • Float(String s) - Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Float.parseFloat example

public class StringToFloat {

 public static void main(String[] args) {
  String num = "-67.789788F";
  try{
   float value = Float.parseFloat(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

value -67.78979

Here you can see that while converting to float number has been rounded off. So be informed that some precision may be lost while converting as float as float is single precision represented by 32 bits (4 bytes) if you want more precision then you may use Double or even better BigDecimal.

Float.valueOf() example

public class StringToFloat {

 public static void main(String[] args) {
  String num = "45.78";
  try{
   Float value = Float.valueOf(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

value 45.78

Note that here value is a Float class object.

NumberFormatExcpetion

If conversion fails then NumberFormatExcpetion is thrown. So, it is better to enclose your conversion code with in a try-catch block.

Example code

public class StringToFloat {

 public static void main(String[] args) {
  String num = "45.78e";
  try{
   Float value = Float.valueOf(num);
   System.out.println("value " + value);
   System.out.println("value " + value.floatValue());
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

Error while conversion For input string: "45.78e"

That's all for this topic Converting string to float - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting string to int - Java Program
  2. Converting string to bytearray - Java Program
  3. Count number of words in a String
  4. String join() method in Java 8
  5. Searching within a String using indexOf(), lastIndexOf() and contains() methods

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment