Mridang Agarwalla
Mridang Agarwalla

Reputation: 44978

Trouble printing the value of a Long division and multiplication

I have trouble figuring out why a simple division like this one always returns 0.

System.out.println(4091365376L / 4091495462L * 100L);

I suffixed all numbers with Ls so they're treated as Longs. I keep getting a zero.

I'm trying to calculate the percentage of 4091365376L to 4091495462L. My values are Longs but I'm just looking for a simple Integer value.

Upvotes: 3

Views: 1114

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

You are a victim of integer rounding (actually: truncation). Try this:

System.out.println(4091365376L * 100L / 4091495462L);

Prints 99. Or cast to double implicitly:

System.out.println(100.0 * 4091365376L / 4091495462L);

Giving 99.99682057572328. Your problem is that 4091495462L is slightly bigger than 4091365376L so when diving them, the result is truncated to 0 (try 3 / 4, if you are not convinced). and 0 times 100 is...

Upvotes: 7

Jonathon Faust
Jonathon Faust

Reputation: 12545

In integer math:

4091365376 / 4091495462 = 0
0 * 100 = 0

You're expecting

4091365376 / 4091495462 = 0.9999682057572327
0.9999682057572327 * 100 = 99.99682057572327

but you can't do that with integers (or long integers). Use doubles if you want a double value.

Upvotes: -1

Wug
Wug

Reputation: 13196

Order is important, as is type. The output of a long divided by a long is a long. The result of the division you're performing is 0, and 0 * 100 == 0. You would be much better off using something like this:

System.out.println((long) (4091365376.0 / 4091495462.0 * 100));

Upvotes: -1

aioobe
aioobe

Reputation: 420971

4091365376L / 4091495462L * 100L
\_______________________/       |
      0.99... = 0               |
      \_________________________/
                    0

You could express it like

100 * 4091365376L / 4091495462L

then it would become

100 * 4091365376L / 4091495462L
\_______________/              |
  409136537600L                |
  \____________________________/
          99.99... = 99  

Upvotes: 4

Related Questions