0

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.

Vivek Vermani
  • 1,934
  • 18
  • 45
  • You use native but I think you mean primitive? That's not what native means. – Taylor Jan 14 '14 at 02:52
  • Just do the primitive conversion. What do you think the wrapper class is wrapping, exactly? A primitive long. You can't get away from doing that conversion. – kenm Jan 14 '14 at 02:55

4 Answers4

1

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

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
1

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:

  • You might want to round instead of just casting. (double to long conversion)
  • I see you have a 'realtedCd' object which means you might be dealing with money or arithmetic operations. If so, I'd advise using BigDecimal instead of doubles for precision Double vs. BigDecimal?
Community
  • 1
  • 1
1

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.

Wisienkas
  • 1,602
  • 2
  • 17
  • 22
0

You can do like this:

Long l = new Double(relatedCd.getDouble(value)).longValue();

Java autoboxing will help you do other things.