Scenario: You’re developing a program that reads and processes large financial data. You have a number that represents currency and may have up to 2 decimal places. What data type would you use, and why?
Answer:
In this scenario, the best choice would be BigDecimal. BigDecimal is designed for handling precise decimal numbers, especially when you need to avoid floating-point inaccuracies (which can occur with float or double). It’s particularly useful for financial applications.
BigDecimal price = new BigDecimal("123.45");
BigDecimal discount = new BigDecimal("10.5");
BigDecimal finalPrice = price.subtract(discount);
System.out.println(finalPrice); // Output: 112.95
Using float or double would introduce rounding errors in financial calculations, making BigDecimal the more appropriate choice.