Sub topic 5
Integer, Long, Double, and Decimal
This chapter assumes you can declare variables and write simple expressions in Apex, as covered earlier in this tutorial. You can run every snippet in Anonymous Apex in the Developer Console. Apex has four numeric primitive types. Picking the wrong one causes overflow, rounding drift, or null reference errors, and this chapter shows how each of those happens.
The four numeric types
| Type | Size and form | Typical use | Literal |
|---|---|---|---|
| Integer | 32-bit signed whole number | Counters, loop indexes, list positions | `42` |
| Long | 64-bit signed whole number | Large counts, timestamps in milliseconds | `8000000000L` |
| Double | 64-bit floating-point number | Scientific or approximate values, `Math` results | `Double d = 0.5;` |
| Decimal | Arbitrary-precision number with a scale | Currency, percentages, exact values | `19.99` |
An Integer holds values from -2,147,483,648 to 2,147,483,647. A Long holds values from -2^63 to 2^63 - 1. A Decimal carries a scale, which is the number of digits after the decimal point. Currency and number fields on SObjects are read into Decimal variables, so Decimal is the type you will meet most often in business logic.
A literal with a decimal point, such as 19.99, is a Decimal. A whole-number literal is an Integer unless it is too large or ends in L. Omitting the L on a large literal is a compile error, because the literal is read as an Integer first.
Integer count = 5;
Long population = 8000000000L;
Double ratio = 0.5;
Decimal price = 19.99;
System.debug(count + ' ' + population + ' ' + ratio + ' ' + price);Widening between numeric types
Apex converts a value implicitly when the target type can hold every value of the source type. The order is Integer, then Long, then Double, then Decimal.
Going the other way needs an explicit method call. Assigning a Long to an Integer variable is a compile error. Use a conversion method instead.
Integer small = 7;
Long widened = small;
Decimal asDecimal = widened;
Long big = 3000000000L;
Integer narrowed = big.intValue();
System.debug(narrowed);
Decimal price = 19.99;
System.debug(price.intValue());
System.debug(price.doubleValue());intValue() on a Decimal drops the fraction. It does not round. intValue() on a Long that does not fit in 32 bits gives a value that does not match the original, so check the range before you narrow.
Integer overflow
Integer arithmetic does not throw an error when the result is out of range. The result wraps around to the other end of the range. This produces wrong data without any warning.
Integer big = 2147483647;
Integer wrapped = big + 1;
System.debug(wrapped);
Long bigLong = big;
Long safe = bigLong + 1;
System.debug(safe);The first value printed is negative. If a sum or product could pass about two billion, declare the variables as Long before you do the arithmetic. Converting the result afterward is too late, because the wrap has already happened.
Why Double is a poor choice for money
A Double stores a binary approximation. Many decimal fractions, such as 0.1, have no exact binary form, so small errors build up.
Double a = 0.1;
Double b = 0.2;
Double sum = a + b;
Double target = 0.3;
System.debug(sum == target);
System.debug(Math.abs(sum - target) < 0.000001);
Decimal x = 0.1;
Decimal y = 0.2;
System.debug(x + y == 0.3);The first comparison prints false, the tolerance check prints true, and the Decimal comparison prints true. When you must compare Doubles, compare the difference to a small tolerance. For anything the business treats as exact, use Decimal.
Note that writing Double d = 0.1 + 0.2; does not show this effect. The literals are Decimals, so Apex adds them exactly and then converts the result. The error appears only when the operands are Double variables.
Working with Decimal scale and rounding
A Decimal keeps the scale it was given. Arithmetic can produce long results, so set the scale yourself when you present or store a value. setScale takes the number of places and an optional rounding mode.
Decimal total = 10.00;
Decimal rate = 0.075;
Decimal tax = (total * rate).setScale(2, RoundingMode.HALF_UP);
System.debug(tax);
System.debug(tax.scale());
Decimal third = total.divide(3, 4, RoundingMode.HALF_UP);
System.debug(third);setScale(2) with no mode uses HALF_EVEN, which rounds exact halves to the nearest even digit. This can surprise users who expect 2.5 to become 3. Pass RoundingMode.HALF_UP when you want the usual schoolbook rounding.
Use divide(divisor, scale, roundingMode) when a quotient might not terminate, such as 10 divided by 3. It lets you choose the result's scale directly.
Comparison with == looks at the numeric value. 1.0 and 1.00 are equal even though their scales differ.
Null and numeric types
Numeric variables start as null, not zero. Arithmetic on a null throws a System.NullPointerException. Fields you read from records can also be null, for example an empty Currency field.
Decimal discount = null;
Decimal zero = 0;
Decimal safeDiscount = discount ?? zero;
System.debug(safeDiscount + 5);
Integer attempts;
System.debug(attempts == null);The ?? operator supplies a fallback when the left side is null. Apply it where you read a value that might be missing, so the rest of the calculation can assume a real number.
Common mistakes
- Using Integer for a running total that can grow large, then seeing negative numbers appear.
- Calling
intValue()on a Decimal and expecting rounding. - Comparing Double values with
==after arithmetic. - Adding to a variable that was never initialized, which fails with a null reference error.
- Accepting the default
HALF_EVENmode when finance rules requireHALF_UP.
Exercise
A loop adds 1,500,000,000 to an Integer variable twice and the final value is negative. What went wrong, and how do you fix it?
Show answer
The sum is 3,000,000,000, which is larger than the Integer maximum of 2,147,483,647. Apex wraps the result around without an error, so it becomes negative. Declare the variable as Long (for example Long total = 0;) before the additions, so the arithmetic is done in 64 bits.
Exercise
What do Decimal d = 2.5; d.setScale(0) and d.setScale(0, RoundingMode.HALF_UP) return, and why do they differ?
Show answer
The first returns 2 and the second returns 3. With no rounding mode, setScale uses HALFEVEN, which rounds a value exactly halfway to the nearest even digit, so 2.5 becomes 2. HALFUP always rounds an exact half away from zero, so 2.5 becomes 3.