
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert String to Float in Java
In this article, we will learn how to convert a string to a float-type number in Java. We will use the Float.parseFloat() method to perform this conversion.
Float.parseFloat() method
The Float.parseFloat() method belongs to the Float class in Java and is used to convert a string representation of a number into a primitive float. If the string does not contain a valid float representation, it throws a NumberFormatException.
NumberFormatException: Thrown to show that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Steps to convert a string to a float-type number
The following are the steps to convert a string to a float-type number
-
Step 1: Declaring and Initializing a String Variable: We start by declaring a string that holds a numerical value in text format. This value will be converted into a float. The variable str holds a string value "111.8", which represents a floating-point number.
String str = "111.8";
-
Step 2: Converting the String to a Float Using parseFloat(): We then call the Float.parseFloat() method to convert the string into a float. The method Float.parseFloat() takes the string str as an argument and converts it into a float. If str contains a non-numeric value, it will throw a NumberFormatException.
float floatVal = Float.parseFloat(str);
-
Step 3: Printing the Converted Float Value: We print the converted float value to the console using System.out.println(). This prints the value of floatVal, which now holds the float representation of the original string "111.8". The output will display the converted float value on the console.
System.out.println("Float: " + floatVal);
Java program to convert a string to a float-type number
The following is an example of converting a string to a float-type number ?
public class Demo { public static void main(String args[]) { String str = "111.8"; float floatVal = Float.parseFloat(str); System.out.println("Float: "+floatVal); } }
Output
Float: 111.8
Advertisements