Money is a Decimal
Write Apex · Beginner · 10 min · Runs in your Salesforce Developer org · Free
Scenario. Sales operations needs the same cent-level result in Apex and in its finance export.
Round Opportunity tax and total with HALF_UP, and see how plain setScale(2) rounds a tie differently.
What you will learn
Salesforce currency fields use Decimal. Round money on purpose with setScale(2, RoundingMode.HALF_UP), so a half cent always rounds up.
Decimal tax = rawTax.setScale(2, RoundingMode.HALF_UP);
Gotcha. setScale(2) with no rounding mode uses banker's rounding (HALF_EVEN). A tie goes to the even digit, so 1.225 becomes 1.22, not 1.23.
The task
Work out tax and total for an Opportunity amount, then show how two rounding rules treat the same tie.
Examples:
- 249.50 at 8% →
Tax: 19.96andTotal: 269.46 1.225withRoundingMode.HALF_UP→HALF_UP tie: 1.231.225with plainsetScale(2)→Default tie: 1.22
Requirements:
- Compute tax as
amount * taxRate. Round tax and total to 2 places withRoundingMode.HALF_UP. - Print
Amount:,Tax:andTotal:from your variables. - Round
tieAmountwithHALF_UPand printHALF_UP tie:with the result. - Round
tieAmountwith plainsetScale(2)and printDefault tie:with the result.
Starter code
Decimal amount = 249.50;
Decimal taxRate = 0.08;
Decimal tieAmount = 1.225;
When it passes
The log shows 249.50, 19.96 and 269.46, then 1.23 with HALF_UP and 1.22 with plain setScale(2).
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.