How to calculate a percentage
Short answer
A percentage of a number is the number multiplied by the percentage and divided by 100:
void main() {
double price = 80;
double discount = price * 15 / 100;
IO.println(discount);
IO.println(price - discount);
}Output:
12.0
68.0What share a part is
Divide the part by the whole and multiply by 100:
void main() {
int done = 37;
int total = 120;
double percent = done * 100.0 / total;
IO.println(String.format(Locale.US, "%.1f%%", percent));
}Output:
30.8%%% in the pattern prints the percent sign itself.
Percentage change
Growth or decline is calculated from the old value:
void main() {
double before = 250;
double after = 300;
double change = (after - before) / before * 100;
IO.println(String.format(Locale.US, "%+.1f%%", change));
}Output:
+20.0%Money
For money percentages use BigDecimal and round to cents:
void main() {
var amount = new BigDecimal("1999.99");
var rate = new BigDecimal("12.5");
var fee = amount.multiply(rate).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
IO.println(fee);
}Output:
250.00Common mistake
Dividing integers. Dividing two int values gives an integer — the fractional part is dropped:
void main() {
int done = 37;
int total = 120;
IO.println(done / total * 100);
IO.println(done * 100.0 / total);
}Output:
0
30.833333333333332Functions used in this recipe
- BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
- String.format() — Builds a string from a template with placeholders such as %s and %d.
- Math.round() — Rounds a number to the nearest integer.