BigDecimal Money
Completed
Read prices as text and sum them with BigDecimal; apply 7.5% tax rounded HALF_UP to 2 decimals. Print the subtotal, the tax and the total.
Input
n, then n prices.
Output
Three lines.
Example
Input
3 0.10 0.20 19.99
Output
20.29 1.52 21.81
Editor
Java
Hints
Create BigDecimal from a String, not a double, to keep it exact.
Solution explanation
new BigDecimal(0.1) is 0.1000000000000000055…; new BigDecimal("0.1") is exactly 0.1.
Show solution
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
BigDecimal subtotal = BigDecimal.ZERO;
for (int i = 0; i < n; i++) {
subtotal = subtotal.add(new BigDecimal(sc.next()));
}
BigDecimal tax = subtotal.multiply(new BigDecimal("0.075")).setScale(2, RoundingMode.HALF_UP);
System.out.println(subtotal.setScale(2, RoundingMode.HALF_UP));
System.out.println(tax);
System.out.println(subtotal.add(tax).setScale(2, RoundingMode.HALF_UP));
}
}