0 votes
1 view
in Java by (10.2k points)

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

1 Answer

0 votes
by (46.1k points)

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.

Related questions

0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4.1k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 18, 2019 in Java by Nigam (4.1k points)
0 votes
1 answer
asked Jul 26, 2019 in Java by Ritik (3.5k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...