views:

8555

answers:

4

In java, what is the best way to convert a double to a long?

Just cast? or

double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);
+9  A: 

Assuming you're happy with truncating towards zero, just cast:

double d = 1234.56;
long x = (long) d; // x = 1234

This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.

Jon Skeet
+8  A: 

... And here is the rounding way which doesn't truncate. Hurried to look it up in the Java API Manual:

double d = 1234.56;
long x = Math.round(d);
Johannes Schaub - litb
It doesn't give the same result as a cast. So it depends on what rich wants to do.
ckarmann
yeah. it was thought as an addition to what Jon said :)
Johannes Schaub - litb
+3  A: 

(new Double(d)).longValue() internally just does a cast, so there's no reason to create a Double object.

Michael Myers
A: 

Simply put, casting is efficient than creating a Double object.

Vijay Dev