I am still learning Java, and I read articles on several sites. I found an article in Java Code Geeks that I have a question about. The article explains the principle of opening / closing. The article uses the scenario of applying discounts to the company's product for an example. The first part of the code is as follows:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Discount {
public BigDecimal apply(BigDecimal price) {
BigDecimal percent = new BigDecimal("0.10");
BigDecimal discount = price.multiply(percent);
return price.subtract(discount.setScale(2, RoundingMode.HALF_UP));
}
}
The second part of the code is as follows:
import java.math.BigDecimal;
public class DiscountService {
public BigDecimal applyDiscounts(BigDecimal price,Discount discount) {
BigDecimal discountPrice = price.add(BigDecimal.ZERO);
discountPrice = discount.apply(discountPrice);
return discountPrice;
}
}
The Oracle site says that ZERO in BigDecimal has a value of 0 and a scale of zero. Does this mean that in price.add(BigDecimal.ZERO)we just add 0 to the price that brought? If so, why? Or is it just that you need to abandon decimal places? Or is there some other purpose?
Thanks!
source
share