Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
Matt Avatar asked Nov 27 '11 15:11

Matt


People also ask

Can you convert a string into a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

How do I convert a string to a number in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

How do I convert a string to a number in Python?

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.


2 Answers

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

like image 80
Andrew Avatar answered Oct 09 '22 09:10

Andrew


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();
               }
           }
        }
like image 27
Drona Avatar answered Oct 09 '22 08:10

Drona