How to check if a String is numeric in Java

前端 未结 30 2499
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  隐瞒了意图╮
    2020-11-21 05:54

    Do not use Exceptions to validate your values. Use Util libs instead like apache NumberUtils:

    NumberUtils.isNumber(myStringValue);
    

    Edit:

    Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.

    NumberUtils.isNumber("07") //true
    NumberUtils.isNumber("08") //false
    

提交回复
热议问题