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?
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.
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.
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.
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
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With