apex-decimal-arithmetic-precision
Use when Apex code performs arithmetic on currency, tax, percentage, or quantity values and the result is wrong by a cent, a penny, or a fraction — Decimal scale collapses to 0 after divide, totals don't match the sum-of-line-items, currency-field rounding differs from in-app calculation, or `divide()` throws on a non-existent rounding mode. Triggers: 'apex decimal divide rounded wrong', 'currency calculation off by a penny', 'apex setScale rounding mode', 'integer divided by integer truncated to zero', 'apex Decimal precision lost'. NOT for SOQL aggregate queries (use apex-aggregate-queries), NOT for Flow formula expression rounding (use flow-formula-and-expression-patterns), NOT for multi-currency dated exchange rates (use multi-currency-and-advanced-currency-management).
Best use case
apex-decimal-arithmetic-precision is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Use when Apex code performs arithmetic on currency, tax, percentage, or quantity values and the result is wrong by a cent, a penny, or a fraction — Decimal scale collapses to 0 after divide, totals don't match the sum-of-line-items, currency-field rounding differs from in-app calculation, or `divide()` throws on a non-existent rounding mode. Triggers: 'apex decimal divide rounded wrong', 'currency calculation off by a penny', 'apex setScale rounding mode', 'integer divided by integer truncated to zero', 'apex Decimal precision lost'. NOT for SOQL aggregate queries (use apex-aggregate-queries), NOT for Flow formula expression rounding (use flow-formula-and-expression-patterns), NOT for multi-currency dated exchange rates (use multi-currency-and-advanced-currency-management).
Teams using apex-decimal-arithmetic-precision should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/apex-decimal-arithmetic-precision/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How apex-decimal-arithmetic-precision Compares
| Feature / Agent | apex-decimal-arithmetic-precision | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Use when Apex code performs arithmetic on currency, tax, percentage, or quantity values and the result is wrong by a cent, a penny, or a fraction — Decimal scale collapses to 0 after divide, totals don't match the sum-of-line-items, currency-field rounding differs from in-app calculation, or `divide()` throws on a non-existent rounding mode. Triggers: 'apex decimal divide rounded wrong', 'currency calculation off by a penny', 'apex setScale rounding mode', 'integer divided by integer truncated to zero', 'apex Decimal precision lost'. NOT for SOQL aggregate queries (use apex-aggregate-queries), NOT for Flow formula expression rounding (use flow-formula-and-expression-patterns), NOT for multi-currency dated exchange rates (use multi-currency-and-advanced-currency-management).
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Apex Decimal Arithmetic Precision
Activate when an Apex calculation produces a value that is wrong by a cent, by a fraction, or — more dangerously — looks correct in unit tests but disagrees with a hand-totalled spreadsheet by enough to fail an audit. The skill resolves the calculation by giving Decimal an explicit scale and rounding mode at every step where rounding can occur, separating the "calculate" path from the "store" path, and matching Apex's behavior to the platform's currency-field behavior.
---
## Before Starting
Gather this context before working on anything in this domain:
- The calculation in plain language: what's the formula, and what is the expected output for one or two specific input rows. "Tax = subtotal × rate, rounded to 2 places, banker's rounding" is enough.
- The Decimal *destination*: a currency field with 2 decimal places, a percent field with 4, a number(18,6), or a transient variable. The destination dictates the final scale; intermediates should generally carry more.
- Whether any of the operands could be a literal `1` or `100` (Integer) rather than `1.0` or `100.0` (Decimal). This is the most common source of "the result truncated to 0" reports.
---
## Core Concepts
### Apex Decimal is fixed-precision, scale-tracking
Apex's `Decimal` type is a fixed-point decimal — internally a Java `BigDecimal`. Every Decimal value carries a *scale* (number of digits after the decimal point). Scale is preserved through addition, subtraction, and multiplication. Division is the operation where Apex *requires* you to declare what scale the result should have, because most divisions don't terminate in finite digits.
A Decimal literal in Apex source picks up its scale from how you wrote it:
- `1.5` — scale 1
- `1.50` — scale 2
- `1` — Integer (no scale, not Decimal)
- `1.0` — Decimal, scale 1
Once the value is in a Decimal variable, scale is "sticky" across arithmetic in predictable ways:
- `Decimal a = 1.50; Decimal b = 1.5; Decimal c = a + b;` → `c` is `3.00` (scale 2, the larger of the two)
- `Decimal d = 1.25 * 1.0;` → `d` is `1.250` (scale = sum of operand scales for multiply)
- `Integer e = 10 / 4;` → `e == 2` (Integer / Integer truncates). The compiler does not warn.
### Division requires `divide(divisor, scale, roundingMode)` for non-terminating results
`Decimal.divide(Decimal divisor)` (single-argument) throws `System.MathException: Division does not result in an exact result, set scale and rounding mode for an inexact result` when the result has more digits than the result's natural scale can hold. `1.0 / 3` blows up; `1.0 / 4 == 0.25` works.
Always prefer the three-argument form for any production calculation:
```apex
Decimal result = numerator.divide(denominator, 4, System.RoundingMode.HALF_UP);
```
The two-argument `divide(divisor, scale)` exists but uses `HALF_EVEN` (banker's rounding) silently — fine if that's what you want, dangerous if you assumed `HALF_UP`.
### Rounding modes that matter
| Mode | Behavior | Use for |
|---|---|---|
| `HALF_UP` | 0.5 rounds away from zero | Retail prices, most user-facing money |
| `HALF_EVEN` (banker's) | 0.5 rounds to even neighbor | Tax, GAAP/IFRS reporting, statistics |
| `HALF_DOWN` | 0.5 rounds toward zero | Rare; specific contractual rounding |
| `UP` / `DOWN` | Always away / toward zero | Truncation; commission caps |
| `CEILING` / `FLOOR` | Always up / down (signed) | Inventory ceiling, never-overcharge |
| `UNNECESSARY` | Throws if rounding actually needed | Use to prove no rounding loss occurred |
The platform's currency-field UI uses `HALF_EVEN` for display rounding. If your Apex uses `HALF_UP` and writes to a Currency field, the value persists as you wrote it but a downstream formula that re-rounds via the platform may shift it back. Match the rounding mode end-to-end or accept the difference.
### Scale of currency, percent, and number fields
- Standard `Currency` fields: scale 2 (or more in multi-currency orgs after Dated Exchange Rate conversion — the stored value retains source scale).
- Custom `Number(length, decimal)`: scale = `decimal`.
- Custom `Percent(length, decimal)`: scale = `decimal`. Stored as the displayed value (5.25% → `5.25`, not `0.0525`).
When you write a higher-scale Decimal into a field with smaller scale, the platform truncates **without an explicit rounding mode** at the DML boundary. To control rounding, call `setScale(fieldScale, RoundingMode.X)` *before* assignment.
---
## Common Patterns
### Calculating a line-item total with tax
```apex
public class LineItemCalc {
public static Decimal totalWithTax(Decimal unitPrice, Integer qty, Decimal taxRatePercent) {
// Force Decimal arithmetic — qty alone is Integer.
Decimal subtotal = unitPrice * qty;
Decimal tax = (subtotal * taxRatePercent).divide(100, 6, System.RoundingMode.HALF_EVEN);
Decimal total = (subtotal + tax).setScale(2, System.RoundingMode.HALF_EVEN);
return total;
}
}
```
Notes: intermediate `tax` carries scale 6 to avoid double-rounding; the outer `setScale(2, HALF_EVEN)` aligns to the currency-field display behavior; `qty` (Integer) is implicitly promoted by `unitPrice * qty` because `unitPrice` is already Decimal.
### Splitting a total across allocations without rounding drift
The classic trap: `total / N` rounded to 2 places, then summed back, drifts by `0.01 × (rounding-direction × N)`. Fix by allocating cumulatively and assigning the residual to the last item:
```apex
public static List<Decimal> allocate(Decimal total, Integer parts) {
List<Decimal> out = new List<Decimal>();
Decimal each = total.divide(parts, 2, System.RoundingMode.HALF_DOWN);
Decimal running = 0;
for (Integer i = 0; i < parts - 1; i++) {
out.add(each);
running += each;
}
out.add((total - running).setScale(2, System.RoundingMode.HALF_UP));
return out;
}
```
The list always sums *exactly* to `total`. Useful for revenue allocation, invoice splits, and percentage-of-total reporting.
---
## Decision Guidance
| Situation | Choice | Rationale |
|---|---|---|
| Storing into a currency field | `setScale(2, HALF_EVEN)` before DML | Matches platform display rounding |
| User-visible price (retail) | `setScale(2, HALF_UP)` | Matches consumer expectation |
| Tax calculation | `HALF_EVEN` | Required by most tax authorities; defensible in audit |
| Cumulative average / weighted avg | Carry scale 6+ in intermediates, round at end | Avoid double-rounding error compounding |
| `1 / 3`-style division | Three-arg `divide(d, scale, mode)` | One-arg form throws on non-terminating |
| Equality compare | Round both sides to same scale first | `1.50 == 1.5` is **true** in Apex but `Decimal.valueOf('1.50').equals(1.5)` is **false** |
---
## Recommended Workflow
1. Identify every division in the calculation. For each, decide the result scale and rounding mode based on the destination field — write them down before writing code.
2. Identify every Integer literal (`1`, `100`, `qty`) being divided or multiplied. If the operation could produce a fraction, change the literal to a Decimal (`1.0`, `100.0`) or wrap with `Decimal.valueOf()`.
3. Carry intermediates at scale ≥ 4 even when the final answer is scale 2. Round only at the boundary (UI display, DML write, contract output).
4. Replace any one-argument `divide(d)` with the three-argument form. Search the codebase for `\.divide\([^,]+\)` to find single-arg divides.
5. Add tests for the boundary cases: zero divisor (expect `MathException`), exact-terminating divide (`1.00 / 4`), repeating divide (`1.00 / 3`), half-way value with both `HALF_UP` and `HALF_EVEN` to confirm the chosen mode.
6. If the calculation feeds a Currency field, write a final `setScale(2, HALF_EVEN)` and confirm the stored value matches a hand calculation.
7. Where the calculation is reused, lift it into a `LineItemCalc`-style stateless utility class with a single rounding-mode parameter so the policy is one place, not seven.
---
## Review Checklist
- Every `divide()` call uses the three-argument form (or there is an inline comment explaining why one-arg is safe — e.g. divisor is a literal power of 2).
- Every Integer-typed operand in a fraction-producing operation is either deliberately Integer (count, index) or has been promoted to Decimal.
- Final scale matches the destination field's scale; intermediate scale is at least 2 higher than final.
- The chosen rounding mode is `HALF_EVEN` for tax/financial reporting, `HALF_UP` for consumer-visible prices, or has a comment explaining the deviation.
- Splitting / allocation logic uses the residual-on-last-item pattern; tests assert sum-equals-total to the cent.
- Equality comparisons round both sides to the same scale before comparing, OR use `==` (value-equal) deliberately rather than `.equals()` (scale-equal).
---
## Salesforce-Specific Gotchas
| Gotcha | Behavior |
|---|---|
| Currency fields in multi-currency orgs | `Decimal` reads from a Currency field carry the *record's* currency, not the user's. Apex doesn't auto-convert; use `UserInfo.getDefaultCurrency()` and the `DatedConversionRate` SObject if conversion is needed. |
| `Decimal.valueOf(Double)` | Passes through Java double's binary float, reintroducing `0.1 + 0.2 = 0.30000000000000004` errors. Use `Decimal.valueOf(String)` or a Decimal literal. |
| Aggregate query types | `SUM(Amount__c)` returns Decimal in Apex but `AVG()` always returns scale 6 regardless of source field. Round explicitly when consuming. |
| Formula-field evaluation | Cross-object formulas evaluate at platform-level with `HALF_EVEN`; if Apex pre-computed the same value with `HALF_UP`, expect a 1-cent shift. |
| `==` vs `.equals()` | Apex `==` on Decimal is value-equal (`1.50 == 1.5` is `true`); `.equals()` is scale-strict. Use `==` for "same number" semantics. |
---
## Output Artifacts
- Corrected Apex utility class with explicit `setScale(scale, RoundingMode)` calls at every rounding point.
- Apex test class with parameterized test for: terminating divide, repeating divide, half-way value with chosen mode, zero divisor, large-N allocation summing exactly to total.
- One-paragraph design note: "this calculation uses HALF_EVEN at scale 2 to match the platform's currency-field display behavior" — kept with the class so the next developer doesn't switch modes accidentally.
---
## Related Skills
- `apex/apex-aggregate-queries` — `SUM` and `AVG` return type quirks.
- `data/multi-currency-and-advanced-currency-management` — Dated Exchange Rates and per-record currency.
- `apex/fsc-financial-calculations` — domain-specific (TWR/IRR) financial math built on top of the Decimal primitives covered here.
- `flow/flow-formula-and-expression-patterns` — Flow's formula engine has its own rounding rules; the gap between Flow and Apex causes the most "Apex says X, Flow says Y" tickets.Related Skills
apex-managed-sharing-patterns
Grant row-level access programmatically via __Share records when declarative sharing rules cannot express the policy. NOT for OWD, role hierarchy, or criteria-based sharing rule design.
lwc-imperative-apex
Call Apex methods imperatively from LWC — on button click, lifecycle hooks, or conditional logic. Covers import syntax, cacheable vs non-cacheable, async/await patterns, error handling, loading states, and Promise.all. NOT for wire service (use wire-service-patterns) and NOT for testing Apex mocks (use lwc-testing).
dataweave-for-apex
Use when transforming structured data inside Apex — CSV → JSON, XML → SObject list, JSON → flattened CSV, or schema-mapping a third-party payload to a Salesforce model — and the existing options (`JSON.deserialize`, `Dom.Document`, hand-written loops) are getting unwieldy. Triggers: 'apex transform csv json xml without external library', 'system.dataweave script', 'salesforce native dataweave apex execute', 'transform xml to sobject apex no mulesoft', 'json reshape salesforce apex script'. NOT for MuleSoft Anypoint DataWeave running off-platform (use mulesoft-anypoint-architecture), NOT for Apex JSON serialization basics (use apex-json-serialization), NOT for Bulk API CSV ingest (use bulk-api-2-patterns).
flow-invocable-from-apex
Author @InvocableMethod Apex classes that Flow can call as Actions. Design the input / output variable contract, bulk semantics (one list in, one list out), null handling, and error surfacing. Also covers the inverse direction: calling a flow from Apex via Flow.Interview. NOT for general Apex authoring (use apex-service-selector-domain). NOT for REST-exposed Apex (use apex-rest-resource-patterns).
flow-apex-defined-types
Design and use Apex-Defined Types as Flow variables for structured non-sObject data (HTTP callout payloads, External Service responses, complex configuration). Trigger keywords: apex-defined type, flow variable, @AuraEnabled class, flow http callout response. Does NOT cover building HTTP Callout Actions themselves, External Services schema, or raw Apex invocable methods.
scheduled-apex-failure-detection-and-monitoring
Use when nightly batch / scheduled Apex jobs are failing without anyone noticing — covers why uncaught exceptions in `execute()` go to the debug log instead of email, how to query `AsyncApexJob` for `Status`, `NumberOfErrors`, and `ExtendedStatus`, when to implement `Database.RaisesPlatformEvents` so the platform publishes `BatchApexErrorEvent` on uncaught failures, how to subscribe to that event with an Apex trigger and notify operators, and how to layer a custom watcher schedule on top so silent-failure modes (job that never started, scheduled class deleted, queue stuck on `Queued`) still surface. Triggers: 'nightly batch failed at 2am with no notification', 'how do we know if a scheduled apex job is failing', 'BatchApexErrorEvent vs custom retry logic', 'Setup Apex Jobs only shows last 7 days, where else can I look', 'job is stuck in queued status nobody noticed for a week'. NOT for general Apex exception handling patterns (use apex/apex-exception-handling-and-logging), NOT for Batch Apex authoring or chunking strategy (use apex/batch-apex-design), NOT for Setup → Apex Jobs UI walkthrough as an admin task (use admin/batch-job-scheduling-and-monitoring), NOT for retry logic itself (use apex/scheduled-apex-retry-patterns once authored).
platform-events-apex
Use when publishing or subscribing to Salesforce Platform Events from Apex, comparing Platform Events with Change Data Capture, or designing event-triggered error handling and monitoring. Triggers: 'EventBus.publish', 'platform event trigger', 'CDC vs Platform Events', 'replay ID', 'high-volume event'. NOT for Flow-only publish/subscribe automation.
health-cloud-apex-extensions
Use this skill when extending Health Cloud via Apex: implementing HealthCloudGA managed-package interfaces, automating care plan lifecycle hooks, processing referrals using Industries Common Components invocable actions, or enforcing HIPAA-compliant logging governance for clinical Apex code. Trigger keywords: CarePlanProcessorCallback, HealthCloudGA namespace, ReferralRequest, ReferralResponse, care plan invocable actions, clinical Apex extension, Health Cloud Apex API. NOT for standard Apex triggers or generic Apex development unrelated to Health Cloud managed-package extension points.
fsl-apex-extensions
Use when writing Apex that calls Field Service Lightning scheduling APIs — AppointmentBookingService, ScheduleService, GradeSlotsService, or OAAS — to book, schedule, grade, or optimize service appointments programmatically. Trigger keywords: FSL Apex namespace, GetSlots, schedule service appointment via code, appointment booking API, FSL optimization API. NOT for standard Apex patterns unrelated to FSL, admin-level scheduling policy configuration, or declarative FSL scheduling.
fsc-apex-extensions
Use this skill when extending Financial Services Cloud (FSC) behavior through Apex: customizing financial rollup recalculation, disabling built-in FSC triggers to write custom trigger logic, implementing Compliant Data Sharing (CDS) participant/role integrations, or building custom FSC action handlers. NOT for standard Apex unrelated to the FSC managed package, standard Salesforce sharing rules, or configuring FSC rollups through the Admin UI — use the admin/financial-account-setup skill for declarative rollup setup.
entitlement-apex-hooks
Use this skill when writing Apex triggers or classes that interact with CaseMilestone records — completing milestones, detecting violations, or reacting to SLA state changes. Trigger keywords: CaseMilestone trigger, auto-complete milestone Apex, milestone violation polling, CompletionDate write pattern. NOT for entitlement process admin setup, milestone configuration in Setup UI, or Flow-based milestone actions.
dynamic-apex
Use when building or reviewing code that constructs SOQL/SOSL at runtime, inspects schema metadata via Schema.describe methods, accesses fields dynamically on sObjects, or performs runtime type inspection. Triggers: 'Database.query', 'Schema.getGlobalDescribe', 'Schema.describeSObjects', 'dynamic field access', 'SObjectType', 'DescribeFieldResult'. NOT for static SOQL queries or query performance tuning — use soql-fundamentals or soql-query-optimization.