Table of Contents
How to Convert String to Float in Java?
Syntax
Examples of Java String to Float
Example #4
Home Java javaTutorial Java String to Float

Java String to Float

Aug 30, 2024 pm 03:18 PM
java

String to float conversion is generally used if we have to perform some mathematical calculations on string data that contains float type numbers. There are situations in which we read data in the form of a string, and we need to convert it into float to perform required operations. In these situations, we need to use Java API’s to convert string types to float.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Convert String to Float in Java?

There are mainly four different ways to convert string to float in java:

  • Using Float.valueOf(): This is a built-in static method of Float class that accepts a given string which is to be converted into float and returns a float value corresponding to the passed input string. This method can throw NumberFormatException if the passed string is not a valid number and NullPointerException if null is passed as input. This returns a primitive object of the Float class.
  • Using Float.parseFloat(): This is also a built-in static method of Float class which accepts a given string that is to be converted into float and returns a float value corresponding to the passed input string. This returns a primitive float value, unlike the valueOf () method, which returns a Float object.
  • Using Constructor: This simply involves using the Float class construct that accepts string parameter as input and returns a float.
  • Using java.text.DecimalFormat Class: This method involves creating an instance of java.text.DecimalFormat class, calling parse method of DecimalFormat class which accepts the string to be converted into a float as input and then followed by calling method floatValue to get float value corresponding to the given string.
  • Based on our requirement, any one of the above four mentioned ways can be used to convert float to string.

Syntax

1. Float.valueOf ()

public static Float valueOf(String input) throws NumberFormatException
Copy after login

In the above syntax, input is the string that is to be converted to float. The return type of the above method is an object of the Float wrapper class. 

2. Float.parseFloat()

public static float parseFloat(String input) throws NumberFormatException
Copy after login

In the above syntax, input is the string that is to be converted to float. The return type of the above method is a float value.

3. Using constructor

new Float(String input)
Copy after login

Calling the above constructor with string to be converted to float as input gives float value corresponding to the given string.

4. text.DecimalFormat

DecimalFormat format= new DecimalFormat (“#”);
format.parse(String input).floatValue();
Copy after login

In the above method, first an instance of java.text.DecimalFormat is created, and then the parse method is involved accepting string as input type, then followed by the floatValue () method to get float value.

Note: All the above methods may throw an exception in case an invalid string is passed as input.

Examples of Java String to Float

Below are the various examples of the Java string to float:

Example #1

This example shows how to use the parseFloat() method to convert string to float.

Code:

public class StringToFloatDemo{
public Float convertStringToFloat(String stringvalue){
try{
float floatValue= Float.parseFloat(stringvalue);
return floatValue;
}
catch(NumberFormatException e){
System.out.println ("NumberFormatException occurred.");
System.out.println(stringvalue + " is not a valid number.");
return null;
}
}
public static void main(String args[])
{
StringToFloatDemo demo = new StringToFloatDemo();
String input= "201.5";
float output= demo.convertStringToFloat("201.50");
System.out.println("Float Value of " + input + " is : " + output);
}
}
Copy after login

Output:

Java String to Float

In case of an exception, let us consider if “Edubca” is passed as input to convertStringToFloat function, then it will show the following output:

Java String to Float

Example #2

In this example, we will show how to use the constructor approach to convert string to float.

Code:

public class StringToFloatDemo{
public Float convertStringToFloat(String stringvalue){
try{
float floatValue = new Float(stringvalue);
return floatValue;
}
catch(NumberFormatException e){
System.out.println ("NumberFormatException occurred.");
System.out.println(stringvalue + " is not a valid number.");
return null;
}
}
public static void main(String args[])
{
StringToFloatDemo demo = new StringToFloatDemo();
String input= "200";
float output= demo.convertStringToFloat(input);
System.out.println("Float Value of " + input + " is : " + output);
}
}
Copy after login

Output:

Java String to Float

Similar to example 1, if an invalid string is passed as input, then NumberFormatException will be generated.

Example #3

In this example, we will show how to use the valueOf() method of the Float class to convert string to float.

Code:

public class StringToFloatDemo{
public Float convertStringToFloat(String stringvalue){
float floatValue;
try{
floatValue= Float.valueOf(stringvalue);
return floatValue;
}catch (NumberFormatException e)
{
System.out.println ("NumberFormatException occurred.");
System.out.println(stringvalue + " is not a valid number.");
return null;
}
}
public static void main(String args[])
{
StringToFloatDemo demo = new StringToFloatDemo();
String input= "200";
float output= demo.convertStringToFloat(input);
System.out.println("Float Value of " + input + " is : " + output);
}
}
Copy after login

Output:

Java String to Float

Similar to example 1 and 2, if an invalid string is passed as input, then NumberFormatException will be generated.

Example #4

In this example, we will show how to use the DecimalFormat class to convert string to float.

Code:

import java.text.DecimalFormat;
import java.text.ParseException;
public class StringToFloatDemo{
public Float convertStringToFloat(String stringvalue){
float floatValue;
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
floatValue = decimalFormat.parse(stringvalue).floatValue();
return floatValue;
} catch (ParseException e) {
System.out.println("Parse Exception Occurred");
System.out.println(stringvalue + " is not a valid number.");
return null;
}
}
public static void main(String args[])
{
StringToFloatDemo demo = new StringToFloatDemo();
String input= "200";
float output= demo.convertStringToFloat(input);
System.out.println("Float Value of " + input + " is : " + output);
}
}
Copy after login

Output:

Java String to Float

In case an invalid String is passed as input, then Parse Exception will be generated.

Let us consider the case when we pass “Edubca” instead of 200 as input to the above program; then the below error will be generated:

Java String to Float

The above is the detailed content of Java String to Float. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles