Question
Why does dividing two long variables in Java return 0?
long a = 3004230;
long b = 6793368;
long c = (a / b) * 100;
Answer
When dividing two long variables in Java, the result is also a long. If the division results in a decimal, it will be truncated to an integer, often resulting in 0. This guide explains why this happens and how to obtain a correct result.
long a = 3004230;
long b = 6793368;
double c = ((double) a / b) * 100; // Correctly divides without truncation.
Causes
- Integer Division: In Java, dividing two integers (or long types) will yield an integer result. Any fractional part is discarded, leading to potential issues when the numerator is smaller than the denominator.
- Incorrect Type Casting: If either value is treated as an integer, the division will still follow the integer division rules.
Solutions
- Use floating-point arithmetic by casting at least one of the operands to a double before performing the division. For example: ```java long a = 3004230; long b = 6793368; double c = ((double) a / b) * 100; ```
- Perform the multiplication before the division to maintain precision: ```java long a = 3004230; long b = 6793368; double c = (double) (a * 100) / b; ```
Common Mistakes
Mistake: Assuming all divisions yield a non-zero result without considering operand types.
Solution: Always check the types of the operands before division. Cast them to double if a non-integer result is expected.
Mistake: Performing multiplication after division which results in less precision.
Solution: Multiply before dividing to preserve precision.
Helpers
- Java
- long division
- divide long variables Java
- integer division
- Java division problems