Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 761
Steve McLeod Avatar asked May 02 '12 14:05

Steve McLeod


People also ask

How do you find the percentage of 2 Places?

Calculate percentages by dividing the fraction's numerator by its denominator, as in 16/64 = 16 divided by 64, or 1/4, or . 25 or 25 percent (%). Find the percentage of a portion of an object by dividing the area of the portion by the area of the whole original object.

How do you calculate percentage exceed?

First, subtract the budgeted amount from the actual expense. If this expense was over budget, then the result will be positive. Next, divide that number by the original budgeted amount and then multiply the result by 100 to get the percentage over budget.

How is percentage calculated in Java programming?

Percentage = (Obtained score x 100) / Total Score To get these parameters (inputs) from the user, try using the Scanner function in Java.

How do you convert a double to a percent in Java?

The following code sample shows how to format a percentage. Double percent = new Double(0.75); NumberFormat percentFormatter; String percentOut; percentFormatter = NumberFormat.


1 Answers

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.

like image 165
NPE Avatar answered Sep 19 '22 21:09

NPE