Numbers
By the end of this lesson, you'll be able to:
- Choose the correct numeric type (Integer, Decimal, Long, Double) for a given value
- Perform basic arithmetic with numeric variables
- Explain why Decimal is generally preferred over Double for money
Prerequisites: "What Is a Variable?"
The four numeric types
| Type | Holds | Typical use |
|---|---|---|
Integer |
Whole numbers, up to about 2.1 billion | Counts, ages, quantities |
Long |
Whole numbers, much larger than Integer | Very large IDs or counts |
Decimal |
Fixed-precision fractional numbers | Money, always |
Double |
Floating-point fractional numbers | Scientific/approximate values |
A real business example: Banking
Decimal accountBalance = 1042.55;
Integer numberOfTransactions = 12;
accountBalance is a Decimal, never a Double — banking math needs exact precision, and Double can introduce tiny rounding errors from how computers represent fractional numbers internally. numberOfTransactions is a whole count, so Integer fits naturally.
Common mistakes
- Using Double for money. This is the single most common numeric mistake in Apex —
Doublerounding errors can silently produce financial figures that are off by fractions of a cent, which compounds into real, confusing bugs. - Assuming Integer division gives a fractional result.
7 / 2using twoIntegers gives3, not3.5— division truncates unless at least one operand is aDecimalorDouble.
Integer division truncates
Integer result = 7 / 2;
System.debug(result); // 3, not 3.5
Decimal preciseResult = 7.0 / 2;
System.debug(preciseResult); // 3.5
Integer division discards the remainder entirely. Making either operand a Decimal (7.0 instead of 7) forces Apex to do fractional division instead.
Exercise
Declare a Decimal called pricePerUnit (12.50) and an Integer called quantity (4). Calculate and debug the total cost.
Show hint
Decimal * Integer works fine in Apex — the result comes out as a Decimal.
Numbers Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Apex has four numeric types — Integer for whole numbers, Decimal for precise fractional values (like money), Long for very large whole numbers, and Double for less-precise fractional values — and picking the right one matters more than it might first appear.