Parse String into Number

偶尔善良 提交于 2019-11-30 13:45:54

问题


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 do I parse a string to a generic number, rather than something specific like an integer or float?


回答1:


Number cannot be instantiated because it is an abstract class. I would recommend passing in Numbers, but if you are set on Strings you can parse them using any of the subclasses,

Number num = Integer.parseInt(myString);

or

Number num = NumberFormat.getInstance().parse(myNumber);

@See NumberFormat




回答2:


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<String> myStrings = new ArrayList<String>(); 
            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();
               }
           }
        }



回答3:


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;
}



回答4:


A simple way is just to check for dot Pattern.matches("\\."). If it has a dot parse as Float.parseFloat() and check for exception. If there is an exception parse as Double.parseDouble(). If it doesn't have a dot just try to parse Integer.parseInt() and if that fails move onto Long.parseLong().




回答5:


you can obtain Number from String by using commons.apache api -> https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/index.html

Usage:

String value = "234568L";  //long in the form string value
Number number = NumberUtils.createNumber(value);



回答6:


Integer.valueOf(string s)

returns an Integer object holding the value of the specified String.

Integer is specialized object of Number



来源:https://stackoverflow.com/questions/8286678/parse-string-into-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!