Convert Java String to Float Object Example

  1. /*
  2.   Convert Java String to Float example
  3.   This example shows how we can convert String object to Float object.
  4. */
  5.  
  6. public class JavaStringToFloatExample {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. //We can convert String to Float using one of the following ways.
  11. //1. Construct Float using constructor.
  12. Float fObj1 = new Float("100.564");
  13. System.out.println(fObj1);
  14.  
  15. //2. Use valueOf method of Float class. This method is static.
  16. String str1 = "100.476";
  17. Float fObj2 = Float.valueOf(str1);
  18. System.out.println(fObj2);
  19.  
  20. /*
  21.   To convert a String object to a float primitive value parseFloat method
  22.   of Float class. This is a static method.
  23.   */
  24. String str2 = "76.39";
  25. float f = Float.parseFloat(str2);
  26. System.out.println(f);
  27.  
  28. //Please note that these methods can throw a NumberFormatException if
  29. //string can not be parsed.
  30.  
  31. }
  32. }
  33.  
  34. /*
  35. Output of the program would be :
  36. 100.564
  37. 100.476
  38. 76.39
  39. */

Post new comment

To combat spam, please enter the code in the image.


Suggested Reading

Oracle Magazine
Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.
Cost: FREE

View/Subscribe
NASA Tech Briefs
Features exclusive reports of innovations developed by NASA and its industry partners/contractors that can be applied to develop new/improved products and solve engineering or manufacturing problems.
Cost: FREE

View/Subscribe
FierceBiotech IT
Is a free, easy to read weekly email service that brings must read biotech IT news to senior biotech, pharma, and IT executives.
Cost: FREE

View/Subscribe
Simply SQL
Simply SQL is a practical step-by-step guide to writing SQL.
Cost: FREE

View/Subscribe
Simply JavaScript
Packed with full-color examples, Simply JavaScript is all you need to start programming in JavaScript the right way.
Cost: FREE

View/Subscribe
PCMag.com's What's New Now
Lance Ulanoff, Editor in Chief of the PC Magazine Network, brings you this twice-weekly roundup of the latest top tech stories, the best new product reviews, plus special offers from Ziff Davis and its partners.
Cost: FREE

View/Subscribe

Could not find what you are looking for? Search Java Examples




Feel Tired? Read Jokes & Inspirational Stories, Play Games!