Java How to check if a String is numeric

摘要: Few Java examples to show you how to check if a String is numeric.

Few Java examples to show you how to check if a String is numeric.

1. Character.isDigit()

Convert a String into a char array and check it with Character.isDigit()

NumericExample.java
package com.mkyong;
public class NumericExample {
    public static void main(String[] args) {
        System.out.println(isNumeric(""));          // false
        System.out.println(isNumeric(" "));         // false
        System.out.println(isNumeric(null));        // false
        System.out.println(isNumeric("1,200"));     // false
        System.out.println(isNumeric("1"));         // true
        System.out.println(isNumeric("200"));       // true
        System.out.println(isNumeric("3000.00"));   // false
    public static boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
        return true;

Output

false
false
false
false
true
true
false

2. Java 8

This is much simpler now.

	public static boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        return str.chars().allMatch(Character::isDigit);

3. Apache Commons Lang

If Apache Commons Lang is present in the claspath, try NumberUtils.isDigits()

pom.xml
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
		<version>3.9</version>
	</dependency>
import org.apache.commons.lang3.math.NumberUtils;
	public static boolean isNumeric(final String str) {
        return NumberUtils.isDigits(str);

4. NumberFormatException

This solution is working, but not recommend, performance issue.

	public static boolean isNumeric(final String str) {
        if (str == null || str.length() == 0) {
            return false;
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;

上一篇: JSON.simple – How to parse JSON
下一篇: Java Check if a String is empty or null
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号