BigDecimal
In this chapter you will learn:
BigDecimal class
BigDecimal represents immutable, arbitrary-precision signed decimal numbers.
BigDecimal is useful for monetary values. The following code shows that floating-point-based invoice calculations leading to confusing results.
import java.text.NumberFormat;
//from ja v a 2 s .c om
public class Main {
public static void main(String[] args) {
double total = 123.45;
double discount = total * 0.01;
double beforeTax = total - discount;
double salesTax = beforeTax * 0.13;
double result = beforeTax + salesTax;
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
System.out.println("Subtotal: " + currencyFormat.format(total));
System.out.println("Discount: " + currencyFormat.format(discount));
System.out.println("SubTotal after discount: " + currencyFormat.format(beforeTax));
System.out.println("Sales Tax: " + currencyFormat.format(salesTax));
System.out.println("Total: " + currencyFormat.format(result));
}
}
The output:
BigDecimal and monetary values
Never using float or double to represent monetary values.
The following code uses BigDecimal to do the invoice calculations
import java.math.BigDecimal;
import java.math.RoundingMode;
/*from j av a 2s . co m*/
public class Main {
public static void main(String[] args) {
BigDecimal total = new BigDecimal("123.45");
BigDecimal discountPercent = new BigDecimal("0.10");
BigDecimal discount = total.multiply(discountPercent);
discount = discount.setScale(2, RoundingMode.HALF_UP);
BigDecimal beforeTax = total.subtract(discount);
beforeTax = beforeTax.setScale(2, RoundingMode.HALF_UP);
BigDecimal salesTaxPercent = new BigDecimal("0.05");
BigDecimal salesTax = beforeTax.multiply(salesTaxPercent);
salesTax = salesTax.setScale(2, RoundingMode.HALF_UP);
BigDecimal result = beforeTax.add(salesTax);
result = result.setScale(2, RoundingMode.HALF_UP);
System.out.println("Subtotal: " + total);
System.out.println("Discount: " + discount);
System.out.println("SubTotal after discount: " + beforeTax);
System.out.println("Sales Tax: " + salesTax);
System.out.println("Total: " + result);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » BigDecimal BigInteger