How to convert a double to long without casting?

rich picture rich · Nov 26, 2008 · Viewed 334.5k times · Source

What is the best way to convert a double to a long without casting?

For example:

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

Answer

Jon Skeet picture Jon Skeet · Nov 26, 2008

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.