Matt
Matt

Reputation: 11347

Parse String into Number

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?

Upvotes: 23

Views: 72504

Answers (6)

AlexR
AlexR

Reputation: 115378

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

Upvotes: 4

Andrew
Andrew

Reputation: 13853

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

Upvotes: 47

Venks
Venks

Reputation: 396

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

Upvotes: 5

Drona
Drona

Reputation: 7234

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

Upvotes: 7

Max
Max

Reputation: 842

Integer.valueOf(string s)

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

Integer is specialized object of Number

Upvotes: 1

Justin Thomas
Justin Thomas

Reputation: 5848

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().

Upvotes: 2

Related Questions