The percentage is a basic mathematical concept that is defined as “a number/ratio that is expressed as a fraction of 100”. It is represented using the symbol “%”. Calculating percentages is a day-to-day task that is used in various fields of life. For instance, it is used in data analysis, financial calculations, interest rate calculations, tax calculations, etc. Considering the highlighted significance, this blog post presents a couple of methods to calculate the percentage in Java.
How to Calculate Percentage in Java Using Standard Mathematical Formula
Use the following formula in your Java program to calculate the percentage:
percentage = (parts/whole) * 100
Example 1: Calculating the Percentage of Given Numbers
In the following code, we use the standard mathematical formula to find the percentage of given numbers:
import java.util.Scanner;
public class CalculatePercentageJava {
public static void main(String args[]) {
double stdMarksObtained; double stdTotalMarks; double stdPercentage;
Scanner scan = new Scanner(System.in);
System.out.print("Please Enter the Obtained Marks ==> ");
stdMarksObtained = scan.nextDouble();
System.out.print("Please Enter Total Marks ==> ");
stdTotalMarks = scan.nextDouble();
stdPercentage = ((stdMarksObtained / stdTotalMarks) * 100);
System.out.println("Total Marks Percentage ==> " + stdPercentage + "%");
scan.close();
}
}
Here, first, we import the Scanner class to get user input. After this, we declare three double-type variables to store the student’s obtained marks, total marks, and marks percentage. Also, we invoke the nextDouble() method a couple of times to get the obtained and total marks from the user. Finally, we use the standard percentage formula to compute the marks’ percentage and print it on the console:
Example 2: Calculating the Percentage of an Array of Values
In the following code, we create an array of integers, indicating the student’s marks in different subjects. Also, we invoke the length property on the given array to find its size/length, as illustrated below:
public class CalculatePercentageJava {
public static void main(String args[]) {
int markObtained = 0;
float marksPercent;
int stdMarks[] = {78, 67, 34, 92, 70, 81};
int arrSize = stdMarks.length;
for (int i = 0; i < arrSize; i++) {
markObtained += stdMarks[i];
}
System.out.println("Marks Obtained == " + markObtained);
marksPercent = (markObtained / (float) arrSize);
System.out.println("Marks Percentage == " + marksPercent + "%");
}
}
We use the for loop to traverse each array element. After this, we use the addition assignment operator within the loop to sum each array element into the “markObtained” variable. Finally, we divide the marks obtained with the array size to find the marks percentage:
Example 3: What is X Percent of Y
Another common percentage problem is finding the “X” percent of “Y”. In this type of problem, we need to modify the standard percentage formula as follows:
public class CalculatePercentageJava {
public static void main(String args[]) {
double empSalary = 50000;
double tax = 14;
double result;
result = ((tax/100)* empSalary);
System.out.println("14% of 50000 is ==> " + result);
}
}
The below output snippet shows that “14” percent of “50000” is “7000”:
How to Calculate Percentage in Java Using BigDecimal Class
The BigDecimal is a built-in Java class that belongs to the “java.math” package. It is specifically designed to perform high-precision arithmetic operations with decimal numbers. It offers several methods to perform different mathematical operations. You can use the multiply() and divide() methods of this class to compute the percentage in Java with high precision.
Example 1: Calculate Percentage of Given Values Using BigDecimal Class
First, we import all the essential classes from the “java.util” package. Then we create a couple of BigDecimal objects and initialize them with respective values:
import java.math.*;
public class CalculatePercentageJava {
public static void main(String[] args) {
BigDecimal marksObtained = new BigDecimal("656");
BigDecimal totalMarks = new BigDecimal("1050");
BigDecimal result = marksObtained.divide(totalMarks, 5, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
System.out.println("Marks Percentage == " + result);
}
}
We invoke the divide() and multiply() methods on the given data to calculate the percentage. In the divide() method we specify a scale of 5 decimal places and rounding mode. One successful execution, the following output appears on our console:
Example 2: Calculate X Percent of Y Using BigDecimal Class
In the following code, we use the divide() and multiply() methods of the BigDecimal class to calculate the “X” percent of “Y”:
import java.math.BigDecimal;
public class CalculatePercentageJava {
public static void main(String[] args) {
BigDecimal empSalary = new BigDecimal("50000");
BigDecimal taxPercent = new BigDecimal("14");
BigDecimal taxAmount = taxPercent.multiply(empSalary).divide(new BigDecimal("100"));
System.out.println("The 14% of 50000 == " + taxAmount);
}
}
The below snippet shows the 14 percent of 50000 using the BigDecimal Class:
This is how you can find the percentage in Java.
Final Thoughts
To calculate percentage in Java, you can use the standard percentage formula (i.e., percentage = (parts/whole) * 100) or BigDecimal class. Use the standard formula if the values to be computed are simple(where high precision is not required). While go for the BigDecimal class, if you want to compute the percentage with high precision. In this post, we’ve shown you the practical implementation of both the discussed methods with examples.