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?
I’d use:
The
100.0forces floating-point math from that point on, and the+ 0.5rounds to the nearest integer instead of truncating.