Suppose I have a BigDecimal amount
and another BigDecimal tax
.
I want to perform the following calculation :
amountWithoutTax = amount - tax
amount
and tax
are supposed to be in the format YYYY.XX
(i.e. precision of 2). So that means amountWithoutTax
should also inherit a precision of 2.
However, in the unlikely case amount
or tax
have 3 or higher precision, amountWithoutTax
would also inherit 3 or higher precision.
What is the appropriate way to handle this situation from a rounding perspective? When it comes to money, $45.134 doesn't make sense as there are no coins with lower value than a cent.
Here are the options I have (I think) using the RoundingMode class :
At the moment we are using CEILING, so it just rounds up. But , to be honest, I am just randomly guessing here. How do I know what is the official / correct way to handle this?
Here are the options I have (I think) using the RoundingMode class : … How do I know what is the official / correct way to handle this?
Ask your team, ask the stakeholder with financial decision-making authority. Different companies & departments have different policies with regard to rounding, truncating, and allocating extra penny.
Tip: HALF-EVEN is known as bankers’ rounding for a reason. But, really, the choice of rounding mode is not the programmer’s call, it is the accountant’s call.
$45.134 doesn't make sense as there are no coins
Incorrect.
In many business scenarios, USD financial amounts are calculated to the third or even the fourth decimal place to track a fraction of a penny.
Indeed, at the gasoline station you may think you are paying USD $ 4.12 per gallon. Actually you are paying USD $ 4.129. They tack nearly an extra penny on to the price posted up on their big signs, using that third decimal place. Read the pump’s fine print to see the full truth.
Alternatively, you can represent money as an integer using a long
. For USD, multiply by 100 to get pennies into the integer. Or multiply by a thousand or ten-thousand for fractional penny.