---
title: "How to check if a String is a numeric type in Java"  
description: "How to check if a String is a numeric type in Java"  
author: "Anonymous User"  
published: 2015-07-24  
updated: 2015-07-24  
canonical: https://www.mindstick.com/forum/23371/how-to-check-if-a-string-is-a-numeric-type-in-java  
category: "java"  
tags: ["java", "string"]  
reading_time: 2 minutes  

---

# How to check if a String is a numeric type in Java

How would you [check if](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) a [String](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) was a number before [parsing](https://www.mindstick.com/interview/1700/what-are-the-standard-ways-of-parsing-xml-document) it?

## Replies

### Reply by Anonymous User

This is generally done with a simple user-defined function (i.e. Roll-your-own "isNumeric" function).\
Something like:

```
public static boolean isNumeric(String str)  {    try    {      double d = Double.parseDouble(str);    }    catch(NumberFormatException nfe)    {      return false;    }    return true;  }
```

However, if you're calling this function a lot, and you expect many of the checks to fail due to not being a number then performance of this mechanism will not be great, since you're relying upon exceptions being thrown for each failure, which is a fairly expensive operation.\
An alternative approach may be to use a regular expression to [check](https://yourviews.mindstick.com/story/2248/never-forget-to-check-these-specifications-before-buying-a-mobile-phone) for validity of being a number:\

```
public static boolean isNumeric(String str){  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.}
```

Be careful with the above RegEx mechanism, though, as it'll fail if your using non-latin (i.e. 0 to 9) digits. For example, arabic digits. This is because the "\d" part of the RegEx will only match [0-9] and effectively isn't internationally numerically aware. (Thanks to OregonGhost for pointing this out!)\
Or even another alternative is to use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric:\

```
public static boolean isNumeric(String str){  NumberFormat formatter = NumberFormat.getInstance();  ParsePosition pos = new ParsePosition(0);  formatter.parse(str, pos);  return str.length() == pos.getIndex();}
```


---

Original Source: https://www.mindstick.com/forum/23371/how-to-check-if-a-string-is-a-numeric-type-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
