013-002-012
Precise Money Calculation with BigDecimal
Hard
Problem Description
Precise Money Calculation with BigDecimal
In this problem: You will create a program using the BigDecimal class for precise monetary calculations without floating-point errors, demonstrating the precision difference from double.
Learning Objective: Understand the floating-point error problem with double and precise decimal calculation with BigDecimal
Overview
The double type has a well-known floating-point error where 0.1 + 0.2 does not exactly equal 0.3. For scenarios requiring precision like money calculations, BigDecimal is used. Creating from strings via the constructor is the accurate approach.
Specifications
- Print 0.1 + 0.2 using double (showing the error)
- Perform the same calculation precisely using BigDecimal
- Apply 10% tax to a product price of 1980 yen (truncate decimals)
- Use compareTo for BigDecimal comparison
Output Format
double: 0.1 + 0.2 = 0.30000000000000004
BigDecimal: 0.1 + 0.2 = 0.3
Price: 1980
Tax (10%): 198
Total: 2178
Equal to 2178? true
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up