Reputation: 359
I have a String object and I need to convert to java.lang.Number.
Number num = null;
Object cellContents = ".475";
If I try to cast the cellContents to Number directly,
num = (Number) cellContents;
it throws an exception:
E[java.lang.ClassCastException: java.lang.String]: : java.lang.ClassCastException: java.lang.String
I searched but could not get a complete answer as to how I can achieve this. Please help!!!
Upvotes: 2
Views: 42937
Reputation: 1506
Firstly, you should cast your object to string.
You can try something like the following code:
Number num = null;
Object cellContents = ".475";
num = cellContents.toString();
num = (Number) num;
Upvotes: 1
Reputation: 3802
You can not simply convert a String into Number directly as they are not in same hierarchy.But good news is Java Wrapper API do most of the task for you automatically IE, convert a valid String into Wrapper you want and throws a NumberFormatException if the passed String is not a valid Number or other Wrapper.
You should use.
Integer.parseInt(String) throws NumberFormatException
OR
Double.parseDouble(String) throws NumberFormatException
they both return Number Integer and Double respectively and both ARE-A Number.
Upvotes: 7
Reputation: 213261
You can't cast a String to a Number
, because they are not covariant (they don't fall in the same inheritance hierarchy).
You can convert the String
to float
or double
using Float#parseFloat()
and Double#parseDouble()
respectively, which is what you would need in most cases.
Using Float#valueOf(String)
and Double#valueOf(String)
creates instances of wrapper classes.
So, depending upon what you need, you can use any of them. I'll show here the first parseXXX
methods:
float strToFloat = Float.parseFloat(".475");
double strToDouble = Double.parseDouble(".475");
BigDecimal
instead:
BigDecimal number = new BigDecimal(".475");
Upvotes: 7
Reputation: 9765
You cannot cast ".475" to Integer. However you can cast it to Float or Double using
float x = Float.parseFloat(".475");
or
double y = Double.parseDouble(".475");
You should search more about Wrapper Classes in Java and AutoBoxing in java to get basic clear. Happy Coding :)
Upvotes: 0
Reputation: 86411
You can't just cast the reference type. You're getting an exception because the String object to which it points is not a Number object.
You can, however, cast the reference to a String, if you know it's a String. You can convert it to a real value with Double.valueOf( String )
or Float.valueOf( String )
. Once you get a double, you can use auto-boxing to turn it into a Double, which isa Number.
Object cellContents = ".475";
Number num = null;
if ( cellContents instanceof String ) {
try {
double d = Double.valueOf( (String) cellContents );
num = (Double) d; // Auto-boxing
}
catch ( NumberFormatException e ) {
...
}
}
else {
...
}
Upvotes: 7