Apex Numeric Types & Operations

Apex Numeric Types and Operations

What Are Numeric Types in Apex?

Numeric types in Apex are used to store numbers—whole numbers, decimal numbers, very large numbers, and precise financial values. These types help you perform calculations, comparisons, and data conversions. 

Types of Numeric Data Types in Apex

Data Type What It Stores Example Precision
Integer Whole numbers Integer age = 25; Up to ± 2,147,483,647
Long Large whole numbers Long population = 7000000000L; Up to ±9,223,372,036,854.
Double Decimal numbers (up to 15 digits) Double pi = 3.14159; ~15 decimal digits
Decimal High-precision decimal values (money, etc.) Decimal price = 19.99; ~28-29 digits

Common Methods and Properties (with Examples)

valueOf() — Converts from string to numeric type

apex 

String str = ‘123’; 

Integer num = Integer.valueOf(str);  // num = 123 

format() — Formats decimal/double values for display

apex 

Decimal price = 1234.567; 

String formatted = price.format();  // “1,234.57” 

toString() — Converts a number to a string

apex 

Double pi = 3.14159; 

String strPi = pi.toString();  // “3.14159” 

Equals() — Checks if two numbers are equal

apex 

Double a = 3.14; 

Double b = 3.14; 

Boolean isEqual = a.equals(b);  // true 

compareTo() — Compares two numeric values

apex 

Decimal x = 10.5; 

Decimal y = 20.7; 

Integer result = x.compareTo(y);  // -1 (x < y) 

Mathematical Operations in Apex

apex 

Integer a = 10; 

Integer b = 5; 

 

Integer add = a + b;         // 15 

Integer subtract = a – b;    // 5 

Integer multiply = a * b;    // 50 

Decimal divide = Decimal.valueOf(a) / b;  // 2.0 

Practice Tasks (For Learners)

1. Convert the string “150” to an Integer using Integer.valueOf().
2. Convert the string “55.75” to a Decimal using Decimal.valueOf().
3. Convert a double value 3.14159 to a string and print the result using toString().
4. Use format() to format the number 1234.5678 and print it.
5. Check if two decimal values 100.00 and 100.00 are equal using equals() and display the result.
6. Compare two double values 5.6 and 9.3 using compareTo() and print the result.
7. Perform and print the results of the following operations using Apex:

Subtraction
Addition
Multiplication
Division

Course Video