search
HomeJavajavaTutorialJava 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

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

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)

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();

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);
}
}

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);
}
}

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);
}
}

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);
}
}

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
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools