java 如何检查字符串是浮点数还是整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43156077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:08:36  来源:igfitidea点击:

How to check a string is float or int?

javastringint

提问by Ali

I have a string and I know that is only contained a number.

我有一个字符串,我知道它只包含一个数字。

I want to check this number is int or float.

我想检查这个数字是整数还是浮点数。

回答by YCF_L

There are many ways to solve your problem for example you can use try{}catch(){}:

有很多方法可以解决您的问题,例如您可以使用try{}catch(){}

Solution 1

方案一

public static void main(String[] args) {
    String str = "5588";
    //check if int
    try{
        Integer.parseInt(str);
    }catch(NumberFormatException e){
        //not int
    }
    //check if float
    try{
        Float.parseFloat(str);
    }catch(NumberFormatException e){
        //not float
    }
}

Solution 2

解决方案2

Or you can use regex [-+]?[0-9]*\.?[0-9]+:

或者您可以使用正则表达式[-+]?[0-9]*\.?[0-9]+

boolean correct = str.matches("[-+]?[0-9]*\.?[0-9]+");

For more details take a look at this Matching Floating Point Numbers with a Regular Expression

有关更多详细信息,请查看使用正则表达式匹配浮点数