BAEL-7226: Code for the improvements of the Percentages article. (#15352)

* BAEL-7226: Code for the improvements of the Percentages article.

* BAEL-7226: Rename Test to follow the convention
This commit is contained in:
Oscar Mauricio Forero Carrillo
2023-12-13 21:22:10 +01:00
committed by GitHub
parent cd85eb8b0b
commit 2495d6fd62
6 changed files with 116 additions and 0 deletions
@@ -0,0 +1,20 @@
package com.baeldung.algorithms.percentage;
import lombok.experimental.ExtensionMethod;
import java.math.BigDecimal;
import java.util.Scanner;
@ExtensionMethod(FastBigDecimalPercentage.class)
public class BigDecimalPercentageCalculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter obtained marks:");
BigDecimal obtained = new BigDecimal(in.nextDouble());
System.out.println("Enter total marks:");
BigDecimal total = new BigDecimal(in.nextDouble());
System.out.println("Percentage obtained :"+ obtained.toPercentageOf(total));
}
}
@@ -0,0 +1,18 @@
package com.baeldung.algorithms.percentage;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalPercentages {
private static final BigDecimal ONE_HUNDRED = new BigDecimal("100");
public BigDecimal toPercentageOf(BigDecimal value, BigDecimal total) {
return value.divide(total, 4, RoundingMode.HALF_UP).multiply(ONE_HUNDRED);
}
public BigDecimal percentOf(BigDecimal percentage, BigDecimal total) {
return percentage.multiply(total).divide(ONE_HUNDRED, 2, RoundingMode.HALF_UP);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.algorithms.percentage;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class FastBigDecimalPercentage {
public static BigDecimal toPercentageOf(BigDecimal value, BigDecimal total) {
return value.divide(total, 4, RoundingMode.HALF_UP).scaleByPowerOfTen(2);
}
public static BigDecimal percentOf(BigDecimal percentage, BigDecimal total) {
return percentage.multiply(total).scaleByPowerOfTen(-2);
}
}