Monday, April 19, 2021

Converting String to float in Java

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 to convert String to float in Java.

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. See example.
  • valueOf(String s)- Returns a Float object holding the float value represented by the String argument s. Throws NumberFormatException if the String does not contain a parsable number. See example.

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.

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

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

Converting String to float in Java using Float.parseFloat method

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.

Converting String to float in Java using Float.valueOf() method

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 while converting String to float

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

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 in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to int in Java
  2. Convert String to Byte Array Java Program
  3. Count Number of Words in a String Java Program
  4. Java join() Method - Joining Strings
  5. Java String Search Using indexOf(), lastIndexOf() And contains() Methods

You may also like-

  1. Read or List All Files in a Folder in Java
  2. Compress And Decompress File Using GZIP Format in Java
  3. How HashSet Works Internally in Java
  4. Difference Between CountDownLatch And CyclicBarrier in Java
  5. Java StampedLock With Examples
  6. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  7. Synchronization in Java - Synchronized Method And Block
  8. Method Reference in Java

No comments:

Post a Comment