Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

java.lang.NumberFormatException – How to solve NumberFormatException

In this example we are going to talk about NumberFormatException. This is an unchecked exception and it can occur when you are trying to convert a String to a numeric value, like an Integer or a Float, but the String is not well formatted for the conversion. For example if you are trying to parse an integer but the string is something like : “123.234” your conversion will fail with a NumberFormatException.

Let’s see some code samples that can cause a NumberFormatException.

1. Converting a String to int

Here is a simple program that will attempt to convert a String to an int.

NumberFormatExceptionExample.java:

package com.javacodegeeks.core.lang.NumberFormatExceptionExample;

public class NumberFormatExceptionExample {
	
	private static final String str = "398475";

	public static void main(String[] args){
		
		int i = Integer.parseInt(str);
		System.out.println("Value parsed :"+i);	
	}
}

This will output :

Value parsed :398475

Everything went well here. So let’s change :

private static final String str = "398475";

to

private static final String str = "0.34";

This is the output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.34"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:492)
	at java.lang.Integer.parseInt(Integer.java:527)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)

Same thing happens if you change to :

private static final String str = "Hello!";

This is the output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.34"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:492)
	at java.lang.Integer.parseInt(Integer.java:527)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)

2. Converting a String to float

NumberFormatExceptionExample.java:

package com.javacodegeeks.core.lang.NumberFormatExceptionExample;

public class NumberFormatExceptionExample {
	
	private static final String str = "123.234";

	public static void main(String[] args){
		
		float i = Float.valueOf(str); //Float.parseFloat(str); 
		
		System.out.println("Value parsed :"+i);	
	}
}

This will output :

Value parsed :123.234

So let’s change :

	private static final String str = "123.234";

to

	private static final String str = "123!234";

This will output :

Exception in thread "main" java.lang.NumberFormatException: For input string: "123!234"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
	at java.lang.Float.valueOf(Float.java:417)
	at com.javacodegeeks.core.lang.NumberFormatExceptionExample.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)

3. How to solve NumberFormatException

As you can see NumberFormatException is thrown every time you are trying to covert a a String to a numeric value. If you are trying to parse an int but the String doesn’t follow the correct format of an integer you will fail. f you are trying to parse a float but the String doesn’t follow the correct format of a float you will fail. Some goes for double or for bytes.

So when you come before this situation you’d better check the input that you give to the parsing method. As a first step, you should check that it’s not null. Then you should try to trim the blank spaces out of the target String. If the String contains more than one numbers you should split the string and parse the numbers individually.

After that you can try to perform more sophisticated input checking using regular expressions. For example if you want an integer value you should use : "-?\\d+" or for a float "-?\\d+.\\d+". Then if your input passes that check you can be sure that you won’t get a NumberFormatException.

Nonetheless, if you want to be sure that your program won’t crush because of that malformed input, you should always handle NumberFormatException in a try-catch block

NumberFormatExceptionExample.java:

package com.javacodegeeks.core.lang.NumberFormatExceptionExample;

public class NumberFormatExceptionExample {
	
	private static final String str = "123!234";

	public static void main(String[] args){
		try{
			float i = Float.valueOf(str); //Float.parseFloat(str); 
		
			System.out.println("Value parsed :"+i);
		}catch(NumberFormatException ex){
			System.err.println("Ilegal input");
			// Discard input or request new input ...
			// clean up if necessary
		}	
	}
}

This will output :

Ilegal input

Download Source Code

This wan an example on java.lang.NumberFormatException and how to solve NumberFormatException. You can download the source code of this example here : NumberFormatExceptionExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close