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
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);
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;
}
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();
}
}
}
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()
.
Integer.valueOf(string s)
returns an Integer object holding the value of the specified String.
Integer is specialized object of Number