2

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!!!

6 Answers 6

7

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 {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

7

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


However, if you are dealing with monetory value, or some other value, where floating point precision is of concern, then you should use BigDecimal instead:

BigDecimal number = new BigDecimal(".475");

1 Comment

Based on the values that I have seen, they are all float or double. Maybe I could suggest this!! Thanks!
7

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.

5 Comments

Integer.parseInt won't work with the example provided (".475")
Because .475 is not an Integer i was generally saying you should use Integer if you have something like "474", but you case ".475" use float or Double
Double.parseDouble() returns a double - not a String or a Number.
@SachinVerma. Please edit your post to correct it. The mistakes pointed out in previous comments is still there.
Still incorrect - Double.parseDouble() returns a double -- not a Double. Autoboxing may obscure this detail.
1

Try

num = new BigDecimal((String)cellContents);

7 Comments

why explicit cast while we can cellContents.toString?
toString can do all sorts of things if the object is not a String. with the cast, you get an error if it is something else.
@Thilo, is it good to introduce BigDecimal to new Programmers when there are much basic things availble??
You mean "basic things" like floating points? Sure, if you want them to learn by pain.
Won't this convert the cellContents to a BigDecimal object. What if cellContents is a float or an int?
|
1

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;

Comments

0

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

3 Comments

Thanks!! But I was looking for a more generic approach that would simply parse the given object to a Number type. So I figured out that it is not possible!!
If you can explain me why you are doing so ? I can help solve your problem
I have a column which is being computed from 2 columns in the database. Since this is a customer database, and the columns are defined as date and float. These 2 columns are divided and the computed column is displayed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.