Reputation: 2014
I have to cast primitive double to Long ( Wrapper) at multiple locations in my code. These are 2 ways I could work with -
linkcatch.setCode(Long.valueOf((long) relatedCd.getDouble(value)));
( casting primitive double to primitive long and then Wrapper Long)
linkcatch.setCode(Long.valueOf(String.valueOf(relatedCd.getDouble(value))));
( casting double to String to Wrapper Long )
Is there any way to cast from native double to Wrapper long without doing the intermediate casting.
I am concerned because there are numerous locations where i need to do this. Thanks.
Upvotes: 0
Views: 1652
Reputation: 64
Just cast and java autoboxing will convert to the Long object type for you. No need to make special libraries or extra methods (stay lean!)
linkcatch.setCode((long)relatedCd.getDouble(value));
Notes:
Upvotes: 1
Reputation: 1751
Found a shorter way to make it. You can use Math.Round to get the long native value. After that you can simply cast it to long
double a = -5.42
Long = (Long)Math.round(a);
However another approach would be too do something like making another class to do the work for you.
public class Util{
public static Long getLong(double a){
return (Long)Math.round(a);
}
}
This way your code would look something like this
linkcatch.setCode(Util.getLong(value));
instead of
linkcatch.setCode(Long.valueOf((long) relatedCd.getDouble(value)));
or
linkcatch.setCode(Long.valueOf(String.valueOf(relatedCd.getDouble(value))));
Hope it helps your to make your code cleaner and easier to manage. Also if you want all the Long values to Round up or down, you have a single place to edit(The Util class), instead of 100 different.
Upvotes: 1
Reputation: 59
You can do like this:
Long l = new Double(relatedCd.getDouble(value)).longValue();
Java autoboxing will help you do other things.
Upvotes: 0
Reputation: 12890
Instead of doing the casting in every java statement, you can create static method which takes a double value as argument, do the casting and return a Long object. In this way, it's easy to maintain and the reusabilty of the code without redundancy
Upvotes: 1