Sub topic 4
Numbers, Currency and Percent: Precision and Scale
This chapter assumes you can create custom fields in Object Manager and know what an object and a record are. It covers the three numeric field types, how precision and scale limit what they accept, and how the choice behaves in formulas and Apex.
The three numeric types
Number, Currency and Percent all store a decimal value with a fixed number of digits. They differ in meaning and presentation.
| Type | Stores | Display | Typical use |
|---|---|---|---|
| Number | A plain decimal value | No symbol | Counts, scores, quantities, measurements |
| Currency | A monetary amount | Currency symbol, plus ISO code in multi-currency orgs | Prices, budgets, revenue |
| Percent | A decimal value shown with a % sign | Value followed by % | Discounts, probabilities, completion rates |
Use the type that matches the meaning of the data. Reports, formulas and users all treat Currency and Percent differently from Number, and changing the type later has consequences (see the chapter on changing field types).
Precision and scale
Two settings define the shape of a numeric field:
- Precision is the total number of digits the field can hold.
- Scale is how many of those digits fall after the decimal point.
The maximum precision is 18 digits. A field with precision 5 and scale 2 holds up to three digits before the decimal point and two after. Its largest value is 999.99.
The Setup page words this differently. It asks for Length (digits to the left of the decimal point) and Decimal Places. The relationship is:
precision = length + decimal placesThe metadata format stores precision and scale directly:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Priority_Score__c</fullName>
<label>Priority Score</label>
<type>Number</type>
<precision>5</precision>
<scale>2</scale>
<required>false</required>
</CustomField>A Currency field uses the same two elements:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Setup_Fee__c</fullName>
<label>Setup Fee</label>
<type>Currency</type>
<precision>16</precision>
<scale>2</scale>
<required>false</required>
</CustomField>What happens when a value does not fit
Two different things can happen, depending on which side of the decimal point is too big.
- Too many digits before the point. The save fails. In Apex, the DML statement throws a
DmlExceptionwith the status codeNUMBER_OUTSIDE_VALID_RANGE. Entering 1000 in the field above fails. - Too many digits after the point. The value is rounded to the field's scale when it is saved. Entering 2.678 in a scale-2 field stores 2.68. The extra digits are lost for good.
Because lost digits cannot be recovered, set the scale to what the data needs, not to what looks tidy. Prices usually need 2 places. Exchange rates or unit costs might need 4 or more. Counts need 0.
Currency specifics
Currency behaves like Number with money-aware features:
- In an org with multi-currency turned on, each record gets a
CurrencyIsoCodefield. A Currency field shows the amount in that record's currency. - Reports can convert amounts to a corporate or user currency using the org's exchange rates. In SOQL, the
convertCurrency()function does this. - Currency fields do not store a currency on their own. They rely on the record's ISO code, or on the org's single currency if multi-currency is off.
Do not use a Number field for money in an org that may ever use multiple currencies. Number fields are never converted, so the amounts become ambiguous.
Percent specifics
A Percent field stores the number you type. If a user types 15, the field stores 15 and displays 15%. Apex and SOQL see 15.
Formulas work differently. Inside a formula, a Percent field is treated as a fraction, so 15% is 0.15. This means a formula can multiply an Amount by a discount directly:
Amount * Discount_Percent__cBe careful when mixing Percent values read in Apex (15) with the same field read in a formula (0.15). Divide by 100 in Apex when you need the fraction.
Numbers in Apex
Numeric fields are returned in Apex as Decimal, which is exact. Use Decimal for Currency and Percent math. Double is a binary floating-point type and cannot represent many decimal fractions exactly.
Double d = 0.1 + 0.2;
System.debug(d); // 0.30000000000000004
Decimal a = 0.1;
Decimal b = 0.2;
System.debug(a + b); // 0.3
Decimal raw = 2.345;
System.debug(raw.setScale(2)); // 2.34 (half-even is the default)
System.debug(raw.setScale(2, System.RoundingMode.HALF_UP)); // 2.35setScale without a rounding mode uses half-even rounding, which rounds a trailing 5 to the nearest even digit. Pass System.RoundingMode.HALF_UP when your business rule is the usual "round 5 up".
Round in code before saving if you want control over the result. Otherwise the platform rounds to the field's scale for you.
Common mistakes
- Using Number for identifiers. Phone numbers, ZIP codes and account numbers lose leading zeros and may need formatting characters. Use Text for any value you do not calculate with.
- Setting the scale too low. A scale of 0 on a unit-price field silently rounds 4.50 to 5 on save.
- Setting precision too small. A field that cannot hold next year's largest value causes save failures that appear without warning.
- Using Number for money. You lose the currency symbol and conversion. Use Currency.
- Forgetting the Percent difference between formulas and code. Check which side you are on before multiplying.
- Storing a calculated value by hand. If the number is always derived from other fields, use a formula or roll-up summary field instead.
Choosing quickly
- Is it money? Use Currency.
- Is it a ratio people read as a percentage? Use Percent.
- Do you calculate with it, or compare it by size? Use Number.
- Is it only an identifier, even if it looks numeric? Use Text.
- Decide the number of decimals the data needs, then add the digits before the point to get the precision.
Exercise
A field must hold unit prices up to 99,999.9999 in a single-currency org. Which type do you choose, and what precision and scale do you set? What happens if a user saves 100000?
Show answer
Use Currency (or Number if you do not want a symbol), with scale 4 and precision 9. That gives 5 digits before the point and 4 after, so the largest value is 99,999.9999. Saving 100000 puts a sixth digit before the decimal point, so the save fails, and in Apex the DML throws a DmlException with status code NUMBEROUTSIDEVALID_RANGE.
Exercise
A Percent field named DiscountPercent_c holds 20 for a 20% discount. In Apex you need the discounted price of an Opportunity Amount. How do you write the calculation, and why does a formula field differ?
Show answer
In Apex, divide by 100 and use Decimal: Decimal price = amount (1 - discount / 100); The field returns 20 in Apex. In a formula, the Percent field is already treated as 0.20, so the formula is Amount (1 - DiscountPercent_c).