Java Program to Convert String to Float Value
Last Updated :
05 Aug, 2021
Given a string “str” in Java, the task is to convert this string to float type.
Methods:
This can be done by two methods as listed below:
- Using parseFloat() Method
- Using valueOf() Method
Let us discuss above two ways of implementing the methods to get a fair understanding of the conversion of string to float values.
Method 1: Using parseFloat()
The parseFloat() method in Float Class is a built-in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float.
Syntax:
public static float parseFloat(String s) ;
Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.
Return type: It returns e float value represented by the string argument.
Exceptions:
- NullPointerException: When the string parsed is null
- NumberFormatException: When the string parsed does not contain a parsable float
Example 1
Java
// Java Program to Convert String to Float Value by
// Implementing parseFloat() method of Float class
// Importing input output classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Input string
String str = "100";
// Returning the float value
// represented by the string argument
float val = Float.parseFloat(str);
// Prints the float value of the string
System.out.println("String is converted to float "
+ val);
}
}
OutputString is converted to float 100.0
Example 2: To show unsuccessful conversion
Java
// Java Program to Convert String to Float Value by
// Implementing parseFloat() method of Float class
// Where Exception Message is thrown
// Importing input output classes
import java.io.*;
// Main class
class GFG {
// Method 1
// To convert string to float
public static void convertStringToFloat(String str) {
float floatValue;
// Try block to check for exceptions
try {
// Convert string to float
// using parseFloat() method
floatValue = Float.parseFloat(str);
// Print the expected float value
System.out.println(
str
+ " after converting into float = "
+ floatValue);
}
// Catch block to handle the exception
catch (Exception e) {
// Print the exception message
// using getMessage() method
System.out.println(
str
+ " cannot be converted to float: "
+ e.getMessage());
}
}
// Method 2
// Main driver code
public static void main(String[] args) {
// Declaring and initializing custom strings values
String str1 = "";
String str2 = null;
String str3 = "GFG";
// Convert string to float
// using parseFloat() method
convertStringToFloat(str1);
convertStringToFloat(str2);
convertStringToFloat(str3);
}
}
Output:
Method 2: Using valueof() method
The valueOf() method of the Float class converts data from its internal form into human-readable form. The valueOf() method converts data from its internal form into a human-readable form. It is a static method that is overloaded within a string for all of Java’s built-in types so that each type can be converted properly into a string.
It is called when a string representation of some other type data is needed-for example during concatenation operation.you can call this method with any data type and get a reasonable String representation valueOf() returns java.lang.Integer, which is the object representative of the integer Few forms of valueOf()
Syntax:
Float.valueOf(str);
Returns:
- It returns string representation of given value
- valueOf(iNum); // Returns the string representation of int iNum.
- String.valueOf(sta); // Returns the string representation of the boolean argument.
- String.valueOf(fNum); // Returns the string representation of the float fnum.
- String.valueOf(data, 0, 15); // Returns the string representation of a specific subarray of the chararray argument.
- String.valueOf(data, 0, 5); // Returns the string of charArray 0 to 5
- String.valueOf(data, 7, 9); // Returns the string of charArray starting index 7 and total count from 7 is 9.
Example
Java
// Java Program to Convert String to Float Value
// Using valuesOf() method
// Importing input output classes
import java.io.*;
// Main class
class GFG {
// Method 1
// To convert String to Float
public static float convertStringToFloat(String str)
{
// Convert string to float
// using valueOf() method
return Float.valueOf(str);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom input string value
String stringValue = "1.0";
// Expected float value
float floatValue;
// Converting string to float
floatValue = convertStringToFloat(stringValue);
// Printing the expected float value
System.out.println(
stringValue + " after converting into float = "
+ floatValue);
}
}
Output1.0 after converting into float = 1.0
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read