Parse String into Number

前端 未结 6 1665
迷失自我
迷失自我 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:21

    You can use the java.text.NumberFormat class. This class has a parse() method which parses given string and returns the appropriate Number objects.

            public static void main(String args[]){
                List myStrings = new ArrayList(); 
                myStrings.add("11");
                myStrings.add("102.23");
                myStrings.add("22.34");
    
                NumberFormat nf = NumberFormat.getInstance();
                for( String text : myStrings){
                   try {
                        System.out.println( nf.parse(text).getClass().getName() );
                   } catch (ParseException e) {
                        e.printStackTrace();
                   }
               }
            }
    

提交回复
热议问题