You've probably come across percentage as a basic concept in Mathematics. But have you ever wondered about "calculating percentages in a Java program"? You might be surprised to know that the percentage is something you will calculate again and again in programming, from grade calculators to discounts, tax, and progress bars.
If you are good with the Math part but struggling to implement it in Java, this article is for you. Here, you will find a complete guide to writing a "Java program to calculate percentages".
In this article, we will discuss the simple mathematical background of percentages, along with the implementation process in Java with examples. Then we will move to the topics where students actually lose points: integer division, rounding, printing the % sign, dividing by zero, and getting an exact answer with BigDecimal. All the outputs below come from actually running the code.
Now, let's explore the topic further!
What Does Mathematics Say About Calculating Percentage?
A percentage is a fraction expressed out of 100. The word itself comes from the Latin "per centum", meaning "by the hundred". The percent sign "%" is used to show it, and you see it everywhere: test scores, sales, battery levels, and interest rates.
We can make it simple with an example. Suppose a student scored 'a' points on a test, and the test was out of 'b' points. Then, the following formula is used to calculate the student's percentage:
Percentage Value Formula: (a / b) x 100
So if you scored 45 out of 60, your percentage is (45 / 60) x 100 = 75%. In Java, the same formula becomes one line:
double percentage = (obtained / total) * 100;
That line looks simple, and it is. But whether it gives the right answer depends on the data types of obtained and total, which is exactly what we will look at next.
How To Calculate Percentage Using Java Code?
Before we move ahead, one thing should be clear. We will implement the above formula ourselves in the Java program. We will not use the % sign in Java code for this, because in Java, % is the remainder (modulus) operator. For example, 7 % 3 gives 1, not "7 percent of 3". The remainder operator and the percentage sign are two different things.
Now, let us look at the following Java program, where the system takes the inputs from the user and gives the percentage as the answer.
Code To Calculate Percentage In Java
import java.util.Scanner; // Scanner For Taking User Inputs
public class Main
{
public static void main(String[] args) {
int div; // Integer Variable To Store The Result
float total, obtained; // Float Data Type Variables
Scanner sc = new Scanner(System.in);
System.out.print("Enter Obtained Score: "); // Taking The Obtained Score
obtained = sc.nextFloat(); // Inserting In The Variable
System.out.print("Enter Total Score: "); // Taking The Total Score
total = sc.nextFloat(); // Inserting In Another Variable
div = (int)((obtained / total) * 100); // Implementing The Formula
System.out.println("Calculated Percentage: " + div + "%"); // Printing The Answer
}
}
Steps Of The Program:
- At first, the Scanner class is imported to take the inputs from the user.
- In the main function, we first declare the variables. The score variables are of the float data type, and the result variable is an int.
- Now, the obtained score is taken from the user and saved in a float variable.
- In the same way, we take the total score from the user and store it in another variable.
- Now, the above formula is applied, the result is cast to an int, and the answer is printed.
Output:
Enter Obtained Score: 45 Enter Total Score: 60 Calculated Percentage: 75%
From the above output, we can see that the two values were taken into the program successfully and saved in the variables. The percentage formula is also working, as the expected answer (75%) is coming.
But try the same program with a score of 2 out of 3:
Enter Obtained Score: 2 Enter Total Score: 3 Calculated Percentage: 66%
The real answer is 66.666...%, but the program prints 66%. The (int) cast does not round. It simply cuts off everything after the decimal point. If your assignment says "round to two decimal places", this program will lose you points.
A Better Version: Use double And Round The Output
Here is the same program with three changes: it uses double instead of float and int, it prints the answer rounded to two decimal places, and it refuses a total of 0 or less. We also moved the formula into its own method, which most instructors like to see.
import java.util.Scanner; // Scanner For Taking User Inputs
public class Main
{
// Returns The Percentage Of obtained Out Of total
static double percentage(double obtained, double total) {
return (obtained / total) * 100;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Points Earned: ");
double obtained = sc.nextDouble();
System.out.print("Enter Total Points: ");
double total = sc.nextDouble();
if (total <= 0) {
System.out.println("Total points must be greater than 0.");
return;
}
double result = percentage(obtained, total);
System.out.printf("Calculated Percentage: %.2f%%%n", result); // 2 Decimal Places
}
}
Output:
Enter Points Earned: 2 Enter Total Points: 3 Calculated Percentage: 66.67%
And when someone types 0 for the total:
Enter Points Earned: 45 Enter Total Points: 0 Total points must be greater than 0.
Notice the %% inside printf. Since printf uses % for its own placeholders (like %.2f), you have to write %% to print one real % sign. We will come back to this in the formatting section. If you are unsure whether to use float or double for this kind of math, we have explained the difference in our guide on float vs double in Java. The short version: use double unless you have a reason not to.
The Integer Division Trap
This is the mistake we see most often in student percentage programs. If both numbers are int, Java does integer division, and the decimal part is thrown away before you multiply by 100.
public class Main
{
public static void main(String[] args) {
int obtained = 45, total = 60;
System.out.println("obtained / total * 100 = " + (obtained / total * 100));
System.out.println("obtained * 100 / total = " + (obtained * 100 / total));
System.out.println("(double) obtained / total * 100 = " + ((double) obtained / total * 100));
System.out.println("obtained * 100.0 / total = " + (obtained * 100.0 / total));
}
}
Output:
obtained / total * 100 = 0 obtained * 100 / total = 75 (double) obtained / total * 100 = 75.0 obtained * 100.0 / total = 75.0
The first line is the trap. 45 / 60 in integer math is 0, and 0 x 100 is still 0. The program compiles and runs without any error, and it quietly prints a wrong answer.
The other three lines all fix it:
obtained * 100 / totalworks because the multiplication happens first (4500 / 60 = 75). But it still cuts off decimals, so 2 out of 3 would give 66.- Casting one value to
doublemakes the whole division a decimal division, as long as you cast before dividing:(double) obtained / total, not(double) (obtained / total). The second one divides as int first and only then turns the 0 into 0.0. - Writing
100.0instead of100does the same thing, as long as the multiplication happens before the division.
Understanding how to implement mathematical formulas in Java is an essential skill, but small details like this are where assignments go wrong. Small type mistakes like this cost points on graded labs, so if your program still prints the wrong number, have a Java tutor check your percentage program for type errors and explain the fix.
How To Add Percentages In Java?
Now, it is time to address other questions related to percentages in Java that are a bit more advanced. After learning how to calculate a percentage with Java, let us see how to add percentages using a Java program.
In Mathematics, adding percentages is a simple operation. Two percentages can be added to each other just like two simple numbers.
Percentage Addition: Percentage1 + Percentage2
Java Code To Add Two Percentages
import java.util.Scanner; // Scanner For Taking User Inputs
public class Main
{
public static void main(String[] args) {
float result;
float a1;
float a2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Percentage: "); // Taking First Float Percentage Value
a1 = sc.nextFloat(); // Saving The Data
System.out.print("Enter Second Percentage: "); // Taking Second Float Percentage Value
a2 = sc.nextFloat(); // Saving The Data
result = a1 + a2; // Adding Two Percentages
System.out.println("Calculated Addition Percentage: " + result + "%"); // Printing The Answer
}
}
Steps Of The Program:
- Here, we again import the Scanner class to get the user input.
- Now, the float variables are declared to hold the user input.
- We first take the first percentage into the program. Later, the second one is taken.
- Now, the two percentages are added to each other in a simple way.
- At last, we print the answer in float format after the addition.
Output:
Enter First Percentage: 25 Enter Second Percentage: 20 Calculated Addition Percentage: 45.0%
From the above output, we can see that the user first provides the two percentages to the program. The result of adding them is printed as the output, and the program runs without any errors.
There is one important rule here, though. Adding percentages only makes sense when both percentages are taken from the same base value. For example, if 25% of a class chose Java and 20% chose Python, then 45% chose one of the two. But if a price goes up by 10% and then up by 10% again, the total increase is not 20%, because the second 10% is taken from the new, bigger price:
public class Main
{
public static void main(String[] args) {
double price = 100.0;
// Two Increases Of 10% One After Another
double afterFirst = price + price * 10 / 100;
double afterSecond = afterFirst + afterFirst * 10 / 100;
// One Increase Of 10% + 10% = 20%
double addedTogether = price + price * 20 / 100;
System.out.printf("10%% then 10%%: %.2f%n", afterSecond);
System.out.printf("20%% at once: %.2f%n", addedTogether);
}
}
Output:
10% then 10%: 121.00 20% at once: 120.00
Two 10% increases give a 21% increase, not 20%. This exact question shows up in word problems, so keep it in mind before you simply add two percentages in your code.
How To Multiply Percentages In Java?
The multiplication of two percentages can't be done as simply as addition. There are a few steps involved in this operation. Let us make it clear with a simple example. Here, we will multiply two percentages, 25% and 20%. Let us look at the following steps:
Step 1: Remove the percentage sign and convert it to decimal format. This means 25% becomes 0.25, and 20% becomes 0.2.
Step 2: Now, multiply these two decimal numbers. That means 0.25 x 0.2 = 0.05.
Step 3: Now, convert the multiplication result back to a percentage by multiplying it by 100. It becomes 0.05 x 100 = 5%.
In real life, this is how you find "a percentage of a percentage". For example, if 25% of students take a CS class and 20% of those students choose the Java section, then 5% of all students are in the Java section.
Java Code To Multiply Two Percentages
import java.util.Scanner; // Scanner For Taking User Inputs
public class Main
{
public static void main(String[] args) {
float temp, result;
float a1;
float a2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Percentage: "); // Taking First Float Percentage Data
a1 = sc.nextFloat();
System.out.print("Enter Second Percentage: "); // Taking Second Float Percentage Data
a2 = sc.nextFloat();
temp = (a1 / 100) * (a2 / 100); // Converting To Decimal & Multiplying
result = temp * 100; // Making It A Percentage Again
System.out.println("Result of Multiplication Percentage: " + result + "%"); // Printing The Float Result
}
}
Steps Of The Program:
- At first, the Scanner class is imported to make the program interactive.
- Now, like the previous programs, the percentage values are taken from the user.
- We first convert the percentages to decimals by dividing them by 100. The multiplication is done in the same statement.
- To finalize the result, we multiply it by 100 to make it a percentage again.
- Now, the answer is printed.
Output:
Enter First Percentage: 25 Enter Second Percentage: 20 Result of Multiplication Percentage: 5.0%
From the above output, we can say that the statements in the program run completely well. After taking the input from the user, the values are converted to decimals, and the multiplication is done. As the result is a float, it comes in decimal format.
Now look what happens with less "friendly" numbers, 33.3% and 15%. The exact answer is 4.995%:
Enter First Percentage: 33.3 Enter Second Percentage: 15 Result of Multiplication Percentage: 4.9950004%
That extra 0.0000004 is not a bug in your logic. It comes from the way float stores decimal numbers in binary. Using double makes this error much smaller, and printing with printf("%.2f%%", result) hides it completely for display.
Other Percentage Calculations You Will Be Asked To Code
Finding "what percent is a of b" is only one type of percentage question. Assignments and coding tests also ask for these, so here they are in one program with a small method for each:
public class Main
{
// What Is p% Of value?
static double percentOf(double p, double value) {
return value * p / 100;
}
// By What Percent Did oldValue Change To Become newValue?
static double percentChange(double oldValue, double newValue) {
return (newValue - oldValue) / oldValue * 100;
}
// value Is The Result After A p% Increase. What Was The Original?
static double originalBeforeIncrease(double value, double p) {
return value / (1 + p / 100);
}
public static void main(String[] args) {
System.out.printf("15%% of 80 = %.2f%n", percentOf(15, 80));
System.out.printf("Price after 20%% off $49.99 = $%.2f%n", 49.99 - percentOf(20, 49.99));
System.out.printf("Score went from 72 to 90: %+.2f%%%n", percentChange(72, 90));
System.out.printf("Score went from 90 to 72: %+.2f%%%n", percentChange(90, 72));
System.out.printf("$54.00 after 8%% tax, before tax = $%.2f%n", originalBeforeIncrease(54.00, 8));
}
}
Output:
15% of 80 = 12.00 Price after 20% off $49.99 = $39.99 Score went from 72 to 90: +25.00% Score went from 90 to 72: -20.00% $54.00 after 8% tax, before tax = $50.00
Here is the formula behind each method, so you can write them from memory:
| Question | Formula | Example |
|---|---|---|
| What is p% of a value? | value x p / 100 | 15% of 80 = 12 |
| Price after a p% discount | price - (price x p / 100) | $49.99 with 20% off = $39.99 |
| Percentage change (increase or decrease) | (new - old) / old x 100 | 72 to 90 = +25% |
| Original value before a p% increase | value / (1 + p / 100) | $54 with 8% tax = $50 before tax |
Look at the two percentage change lines in the output. Going from 72 to 90 is +25%, but going back from 90 to 72 is only -20%. The change is divided by the starting value, and the starting value is different each time. The %+.2f in printf is what adds the + sign for positive numbers.
Calculating The Overall Percentage From Several Scores
Grade calculators are one of the most common Java assignments, and they come with a question that confuses a lot of students: is your overall percentage the total points divided by the total possible points, or the average of each assignment's percentage? They are not the same.
public class Main
{
public static void main(String[] args) {
String[] names = {"Quiz 1", "Lab 1", "Midterm"};
double[] earned = {9, 18, 70};
double[] max = {10, 25, 100};
double totalEarned = 0, totalMax = 0, sumOfPercents = 0;
for (int i = 0; i < earned.length; i++) {
double p = earned[i] / max[i] * 100;
System.out.printf("%-8s %5.1f / %5.1f = %6.2f%%%n", names[i], earned[i], max[i], p);
totalEarned += earned[i];
totalMax += max[i];
sumOfPercents += p;
}
System.out.printf("Overall (total points): %.2f%%%n", totalEarned / totalMax * 100);
System.out.printf("Average of the 3 percents: %.2f%%%n", sumOfPercents / earned.length);
}
}
Output:
Quiz 1 9.0 / 10.0 = 90.00% Lab 1 18.0 / 25.0 = 72.00% Midterm 70.0 / 100.0 = 70.00% Overall (total points): 71.85% Average of the 3 percents: 77.33%
The two answers differ by more than 5 percentage points. The overall percentage (71.85%) counts the midterm more, because it is worth 100 points. The plain average (77.33%) treats a 10-point quiz the same as the 100-point midterm. Read your assignment carefully to see which one it wants. Many courses use total points or weighted categories, not a simple average. If you want to take this further and turn percentages into letter grades, check out our Java program that calculates student grades.
How To Print The % Sign And Format Percentages In Java
Printing the answer looks like the easy part, but it causes its own errors. Java gives you three common ways to display a percentage:
import java.text.NumberFormat;
import java.util.Locale;
public class Main
{
public static void main(String[] args) {
double ratio = 0.7564; // 75.64% Stored As A Fraction
// 1. printf: Use %% To Print A Single % Sign
System.out.printf("printf: %.1f%%%n", ratio * 100);
// 2. String.format: Same Rules, But Gives You A String
String s = String.format("%.2f%%", ratio * 100);
System.out.println("String.format: " + s);
// 3. NumberFormat: Multiplies By 100 And Adds The % For You
NumberFormat pf = NumberFormat.getPercentInstance(Locale.US);
System.out.println("NumberFormat: " + pf.format(ratio));
pf.setMinimumFractionDigits(1);
System.out.println("With 1 digit: " + pf.format(ratio));
}
}
Output:
printf: 75.6% String.format: 75.64% NumberFormat: 76% With 1 digit: 75.6%
A few things to notice here:
printfandString.formatround the value for you. 75.64 printed with%.1fbecomes 75.6.NumberFormat.getPercentInstance()expects a fraction like 0.7564, not 75.64. It multiplies by 100 by itself. If you pass it 75.64, you get "7,564%".- By default,
NumberFormatshows no decimal places, so 75.64% became 76%. UsesetMinimumFractionDigits()to keep decimals.
The most common mistake is writing a single % at the end of a printf string:
public class Main
{
public static void main(String[] args) {
double p = 75.64;
System.out.printf("Score: %.2f%", p);
}
}
Output:
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '%'
The program compiles fine and crashes when it runs. Java reads the last % as the start of a new placeholder and finds nothing after it. Change it to %% and the error is gone. In a plain println with + (like our first program), a single % is fine, because println does not treat % as special.
What Happens If The Total Is Zero?
If the total is 0, the percentage formula divides by zero. What happens next depends on the data type, and the result surprises many students:
public class Main
{
public static void main(String[] args) {
double obtained = 40, total = 0;
System.out.println("double, 40 / 0 * 100 = " + (obtained / total * 100));
System.out.println("double, 0 / 0 * 100 = " + (0.0 / total * 100));
int a = 40, b = 0;
System.out.println("int, 40 * 100 / 0 = " + (a * 100 / b));
}
}
Output:
double, 40 / 0 * 100 = Infinity
double, 0 / 0 * 100 = NaN
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:9)
With double, there is no error at all. You get Infinity or NaN (Not a Number), and your program happily prints "Infinity%". With int, Java throws an ArithmeticException and stops. Either way, the fix is the same: check that the total is greater than 0 before dividing, as we did in the better version above.
What Are Some Percentage Libraries And Tools In Java?
Before we end our discussion, it is worth knowing the tools Java gives you for percentage work beyond plain double math. Most of them are only needed for bigger tasks like statistics, reports, or banking and money calculations. For a class assignment, the formula and printf are usually enough.
BigDecimal (built into Java): When the answer must be exact, like money, where every cent must be right, use java.math.BigDecimal. It stores decimal numbers exactly and lets you choose how to round.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main
{
public static void main(String[] args) {
double obtained = 194, total = 250;
System.out.println("double: " + (obtained / total * 100));
BigDecimal o = new BigDecimal("194");
BigDecimal t = new BigDecimal("250");
BigDecimal p = o.multiply(new BigDecimal("100"))
.divide(t, 2, RoundingMode.HALF_UP); // 2 Decimal Places
System.out.println("BigDecimal: " + p);
BigDecimal third = new BigDecimal("1").multiply(new BigDecimal("100"))
.divide(new BigDecimal("3"), 2, RoundingMode.HALF_UP);
System.out.println("1 out of 3: " + third);
}
}
Output:
double: 77.60000000000001 BigDecimal: 77.60 1 out of 3: 33.33
With double, 194 out of 250 prints as 77.60000000000001. With BigDecimal, it is exactly 77.60. Two tips: create BigDecimal values from strings like "194", not from doubles, and always pass a scale and rounding mode to divide(). Without them, a result like 1 out of 3 (33.333...) never ends, and Java throws an ArithmeticException.
NumberFormat (built into Java): As shown in the formatting section, java.text.NumberFormat turns a fraction into a percent string with the % sign, and it follows the number style of the locale you give it.
Apache Commons Math: This library has a Percentile class in its statistics package. Be careful with the name: a percentile is not a percentage. A percentile tells you where a value stands in a data set (for example, "this score is higher than 90% of the class"). You only need it for statistics work, like ranking test scores.
Google Guava: Guava, a library developed by Google, has a Quantiles class (in com.google.common.math) that also calculates percentiles. Like Apache Commons Math, it is for statistics problems, not for a simple percentage formula.
Where Percentage Programs Usually Break
Before you submit, check your program against this list:
- Dividing two
intvalues, which gives 0 for any score lower than the total. - Casting the result to
intand expecting it to round. It only cuts off the decimals. - Writing a single % at the end of a
printfstring, which crashes the program at runtime. - Not checking for a total of 0 before dividing.
- Adding percentages that come from different base values, like two price increases in a row.
- Passing 75.64 to
NumberFormat.getPercentInstance()instead of 0.7564. - Using the % operator thinking it calculates a percentage. It gives the remainder.
Conclusion
As we saw, "calculating percentages in a Java program" is useful from both the Math and the CS point of view.
To calculate a percentage, you should first be ready with the mathematical formula. If the formula is clear to you, implementing it in Java or any other language becomes a breeze. After that, the only things left to watch are the data types, the rounding, and the % sign when printing.
Make sure the basics are clear before you start a new topic. Even though percentages in Java are one of the simpler concepts, if you have any doubts about Java basics like data types and type casting, clear them up first.
Frequently Asked Questions
- What is the formula to calculate percentage in Java?
- Use (obtained / total) * 100, with at least one of the values as a double. For example, double percentage = (double) obtained / total * 100; works even when obtained and total are int variables.
- Why does my Java percentage program always print 0?
- Both numbers are probably int, so Java does integer division. 45 / 60 becomes 0 before it is multiplied by 100. Cast one value to double, or write 100.0 at the start of the formula, to fix it.
- How do I round a percentage to 2 decimal places in Java?
- For display, use System.out.printf("%.2f%%", percentage) or String.format("%.2f%%", percentage). If you need the rounded number itself, use Math.round(percentage * 100) / 100.0, or BigDecimal with setScale(2, RoundingMode.HALF_UP).
- How do I print the % symbol in Java?
- In println, just put "%" inside the string. In printf or String.format, write %% to print one % sign, because a single % starts a format placeholder and causes an UnknownFormatConversionException at the end of the string.
- Is the % operator in Java used for percentages?
- No. In Java, % is the remainder (modulus) operator, so 10 % 3 gives 1. To calculate a percentage, you divide and multiply by 100 yourself.
- How do I calculate percentage increase in Java?
- Use (newValue - oldValue) / oldValue * 100 with double values. A positive result is an increase, and a negative result is a decrease. Make sure oldValue is not 0 before dividing.

