Overflow-safe way to calculate percentage from two longs in Java

java

Solution

I'd use:

int percentage = (int)(numerator * 100.0 / denominator + 0.5);

The `100.0` forces floating-point math from that point on, and the `+ 0.5` rounds to the nearest integer instead of truncating.

Problem

I have two non-negative longs. They may be large, close to Long.MAX_VALUE. I want to calculate a percentage from the two numbers. Usually I'd do this: ``` long numerator = Long.MAX_VALUE / 3 * 2; long denominator = Long.MAX_VALUE; int percentage = (int) (numerator * 100 / denominator); System.out.println("percentage = " + percentage); ``` This is not correct if numerator is within two order of magnitudes to Long.MAX_VALUE. What's a correct, simple, and fast way to do this?

Original source