ApexSensei

Drills › Write Apex

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.96 and Total: 269.46
  • 1.225 with RoundingMode.HALF_UP → HALF_UP tie: 1.23
  • 1.225 with plain setScale(2) → Default tie: 1.22

Requirements:

  1. Compute tax as amount * taxRate. Round tax and total to 2 places with RoundingMode.HALF_UP.
  2. Print Amount:, Tax: and Total: from your variables.
  3. Round tieAmount with HALF_UP and print HALF_UP tie: with the result.
  4. Round tieAmount with plain setScale(2) and print Default 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).

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Integer division and Math.mod · True, false, and null ›