Parse String into Number

前端 未结 6 1706
迷失自我
迷失自我 2020-12-31 04:51

I have a list which will store Number objects. The list will be populated by parsing a list of strings, where each string may represent any subclass of Number.

How d

6条回答
  •  无人及你
    2020-12-31 05:15

    Something like the following:

    private static Number parse(String str) {
        Number number = null;
        try {
            number = Float.parseFloat(str);
        } catch(NumberFormatException e) {
            try {
                number = Double.parseDouble(str);
            } catch(NumberFormatException e1) {
                try {
                    number = Integer.parseInt(str);
                } catch(NumberFormatException e2) {
                    try {
                        number = Long.parseLong(str);
                    } catch(NumberFormatException e3) {
                        throw e3;
                    }       
                }       
            }       
        }
        return number;
    }
    

提交回复
热议问题