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?
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.
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.
Percentage = (Obtained score x 100) / Total Score To get these parameters (inputs) from the user, try using the Scanner function in Java.
The following code sample shows how to format a percentage. Double percent = new Double(0.75); NumberFormat percentFormatter; String percentOut; percentFormatter = NumberFormat.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With