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;
Decimal accountBalance = 1042.55;— declaresaccountBalanceas aDecimal(fixed-precision, exact fractional number) and sets it to1042.55.Integer numberOfTransactions = 12;— declares a whole-number count as anInteger.
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 result = 7 / 2;— divides twoIntegers. Apex performs integer division here, discarding any remainder, soresultbecomes3, not3.5.System.debug(result);— logsresult, confirming it printed3.- (blank line)
Decimal preciseResult = 7.0 / 2;— writing7.0instead of7makes one operand aDecimal, so this time Apex performs fractional division.System.debug(preciseResult);— logspreciseResult, which prints3.5.
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
Leaderboard
- 1. Monde Masiza 2/2
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.