Double
Learning Content
Last updated: July 28, 2026
Double Data Type
The Double data type is used to store floating-point numbers with decimal values. It supports a very large numeric range and is commonly used for scientific calculations, engineering formulas, statistical analysis, and mathematical computations where approximate precision is acceptable.
Although Double can store decimal values like the Decimal data type, it uses floating-point arithmetic. Because of this, very small rounding differences may occur during calculations. For financial applications, Salesforce recommends using Decimal instead of Double.
💡 LearnFrenzy Insight
Imagine measuring the height of a mountain. You might record the height as:
- 8848.86 metres
- 123.456 kilometres
- 0.0000035 metres
Scientific and engineering measurements often require very large or very small decimal values. The Double data type is designed to efficiently represent these floating-point numbers.
What is a Double?
A Double stores floating-point numeric values. It is suitable for calculations where a wide numeric range is more important than exact decimal precision. Double follows the IEEE 754 standard for double-precision floating-point arithmetic.
Double temperature = 36.75; Double gravity = 9.81; Double pi = 3.14159265358979; Double negativeValue = -45.67; // Negative values are also supported Double scientificNotation = 1.5e-10; // Scientific notation: 0.00000000015
💡 Pro Tip: Double in Apex is a 64-bit (8-byte) floating-point number that follows the IEEE 754 standard. It can represent values from approximately 4.9e-324 to 1.8e+308.
Double Range & Characteristics
A Double occupies 64 bits (8 bytes) of memory and has the following characteristics:
| Property | Value |
|---|---|
| Memory Size | 64-bit (8 Bytes) |
| Minimum Positive Value | ~4.9e-324 |
| Maximum Positive Value | ~1.8e+308 |
| Precision | ~15-16 decimal digits |
| Default Value | null (when declared but not initialized) |
| Standard | IEEE 754 double-precision |
⚠️ Important Note on Precision: Double can represent extremely large and small numbers, but with only about 15-16 digits of precision. This means very large numbers may lose precision in the decimal places.
Why Use Double?
| Reason | Benefit |
|---|---|
| Large Numeric Range | Can represent extremely large and small values (e.g., 1.8e+308 to 4.9e-324) |
| Floating-Point Calculations | Supports scientific and engineering computations with decimal values |
| Mathematical Functions | Suitable for trigonometry, geometry, and statistical calculations |
| Performance | Efficient for many mathematical operations (hardware optimized) |
| Scientific Notation | Can represent very small or very large numbers using exponential notation |
Variable Declaration & Initialization
You can declare and initialize Double variables in several ways:
// Method 1: Declaration with initialization
Double pi = 3.14159265358979;
Double temperature = 25.75;
// Method 2: Declaration without initialization (defaults to null)
Double earthGravity;
earthGravity = 9.81; // Initialization later
// Method 3: Scientific notation
Double avogadro = 6.022e23; // 6.022 × 10^23
Double smallValue = 1.5e-10; // 1.5 × 10^-10
// Method 4: From Integer
Integer count = 100;
Double doubleFromInt = Double.valueOf(count); // 100.0
// Method 5: From String
Double parsed = Double.valueOf("123.45");
📝 Key Points:
- Uninitialized Double variables default to
null, not 0.0. - Always initialize variables before using them in calculations.
- Scientific notation (like
1.5e-10) is useful for very small or large values. - Use descriptive names like
earthGravityoraverageSpeed.
Basic Arithmetic Operations
Doubles support all standard arithmetic operations with floating-point precision:
Double length = 25.5;
Double width = 12.4;
Double height = 5.0;
// Basic Arithmetic
System.debug('Addition: ' + (length + width)); // 37.9
System.debug('Subtraction: ' + (length - width)); // 13.1
System.debug('Multiplication: ' + (length * width)); // 316.2
System.debug('Division: ' + (length / width)); // 2.056451612903226
System.debug('Modulus: ' + (25.5 % 3)); // 1.5
// Complex calculations
Double area = length * width;
Double volume = length * width * height;
System.debug('Area: ' + area); // 316.2
System.debug('Volume: ' + volume); // 1581.0
// Scientific calculations
Double radius = 7.5;
Double circleArea = Math.PI * radius * radius;
System.debug('Circle Area: ' + circleArea); // 176.71458676442586
Output
Addition: 37.9 Subtraction: 13.1 Multiplication: 316.2 Division: 2.056451612903226 Modulus: 1.5 Area: 316.2 Volume: 1581.0 Circle Area: 176.71458676442586
Floating-Point Precision Example
Floating-point numbers are represented in binary, which can cause small rounding differences in decimal calculations. Here's a classic example:
Double value1 = 0.1;
Double value2 = 0.2;
Double result = value1 + value2;
System.debug('0.1 + 0.2 = ' + result); // 0.30000000000000004
Double value3 = 0.3;
System.debug('Is 0.1 + 0.2 == 0.3? ' + (result == value3)); // false
// More precision examples
Double a = 1.03 - 0.42;
System.debug('1.03 - 0.42 = ' + a); // 0.6100000000000001
Double b = 1.0 / 3.0;
System.debug('1.0 / 3.0 = ' + b); // 0.3333333333333333
⚠️ Important: For scientific calculations, this behaviour is generally acceptable. For financial calculations involving currency, use Decimal instead of Double to avoid these precision issues.
Real Salesforce Business Example
🏢 Business Scenario 1: Manufacturing Analytics
A manufacturing application stores product weights and calculates average weight for analytical reporting.
Double totalWeight = 528.75;
Integer totalProducts = 15;
Double averageWeight = totalWeight / totalProducts;
System.debug('Total Weight: ' + totalWeight + ' kg');
System.debug('Number of Products: ' + totalProducts);
System.debug('Average Weight: ' + averageWeight + ' kg'); // 35.25
// Round for reporting
Double roundedAvg = Math.round(averageWeight * 100) / 100.0;
System.debug('Rounded Average: ' + roundedAvg + ' kg'); // 35.25
Output
Total Weight: 528.75 kg Number of Products: 15 Average Weight: 35.25 kg Rounded Average: 35.25 kg
In analytical applications where slight floating-point differences are acceptable, Double is an appropriate choice.
🏢 Business Scenario 2: Sales Performance Analytics
Calculate average sales performance for quarterly reporting.
// Monthly sales data
Double januarySales = 125000.50;
Double februarySales = 135000.75;
Double marchSales = 145000.25;
// Calculate quarterly total and average
Double quarterlyTotal = januarySales + februarySales + marchSales;
Double quarterlyAverage = quarterlyTotal / 3;
System.debug('Q1 Total: $' + quarterlyTotal); // $405001.50
System.debug('Q1 Average: $' + quarterlyAverage); // $135000.50
// Year-over-year growth calculation
Double lastYearQ1 = 380000.00;
Double growthPercent = ((quarterlyTotal - lastYearQ1) / lastYearQ1) * 100;
System.debug('Growth: ' + growthPercent + '%'); // 6.579342105263158%
Output
Q1 Total: $405001.50 Q1 Average: $135000.50 Growth: 6.579342105263158%
🏢 Business Scenario 3: Geography & Distance Calculation
Calculate distance between two locations using GPS coordinates (a common use case for Double).
// GPS Coordinates (Latitude, Longitude)
Double lat1 = 28.6139; // New Delhi
Double lon1 = 77.2090;
Double lat2 = 19.0760; // Mumbai
Double lon2 = 72.8777;
// Approximate distance calculation using Haversine formula
Double earthRadius = 6371.0; // Earth radius in kilometers
Double latDiff = Math.toRadians(lat2 - lat1);
Double lonDiff = Math.toRadians(lon2 - lon1);
Double a = Math.sin(latDiff / 2) * Math.sin(latDiff / 2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(lonDiff / 2) * Math.sin(lonDiff / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
Double distance = earthRadius * c;
System.debug('Distance between Delhi and Mumbai: ' + distance + ' km');
// Approximate output: ~1150 km
Common Double Operations
| Operator/Method | Description | Example | Result |
|---|---|---|---|
+ | Addition | 10.5 + 5.2 | 15.7 |
- | Subtraction | 20.5 - 3.2 | 17.3 |
* | Multiplication | 5.5 * 6.0 | 33.0 |
/ | Division | 20.0 / 4.0 | 5.0 |
% | Modulus | 10.5 % 3.0 | 1.5 |
Math.round() | Round to nearest integer | Math.round(3.7) | 4.0 |
Math.floor() | Round down | Math.floor(3.7) | 3.0 |
Math.ceil() | Round up | Math.ceil(3.2) | 4.0 |
Double.valueOf() | Convert to Double | Double.valueOf("123.45") | 123.45 |
Mathematical Functions with Double
Apex provides many mathematical functions in the Math class that work with Double:
Double value = 25.75;
// Basic Math functions
System.debug('Absolute: ' + Math.abs(-25.75)); // 25.75
System.debug('Square root: ' + Math.sqrt(144.0)); // 12.0
System.debug('Power: ' + Math.pow(2.0, 3.0)); // 8.0
System.debug('Exponential: ' + Math.exp(1.0)); // 2.718281828459045
System.debug('Natural Log: ' + Math.log(10.0)); // 2.302585092994046
// Trigonometric functions
Double angle = 45.0;
Double radians = Math.toRadians(angle);
System.debug('Sin(45°): ' + Math.sin(radians)); // 0.7071067811865475
System.debug('Cos(45°): ' + Math.cos(radians)); // 0.7071067811865476
System.debug('Tan(45°): ' + Math.tan(radians)); // 1.0
// Rounding functions
System.debug('Round: ' + Math.round(25.75)); // 26.0
System.debug('Floor: ' + Math.floor(25.75)); // 25.0
System.debug('Ceil: ' + Math.ceil(25.75)); // 26.0
// Min/Max
System.debug('Min: ' + Math.min(25.75, 10.5)); // 10.5
System.debug('Max: ' + Math.max(25.75, 10.5)); // 25.75
// Random number generation
Double random = Math.random(); // Random value between 0.0 and 1.0
System.debug('Random: ' + random);
Output
Absolute: 25.75 Square root: 12.0 Power: 8.0 Exponential: 2.718281828459045 Natural Log: 2.302585092994046 Sin(45°): 0.7071067811865475 Cos(45°): 0.7071067811865476 Tan(45°): 1.0 Round: 26.0 Floor: 25.0 Ceil: 26.0 Min: 10.5 Max: 25.75 Random: 0.123456789
💡 Pro Tip: The Math class in Apex provides over 30 mathematical functions that work with Double values, making it powerful for scientific and engineering computations.
Double vs Decimal
| Feature | Double | Decimal |
|---|---|---|
| Arithmetic Type | Floating-point (binary) | High-precision (decimal) |
| Precision | ~15-16 digits | Up to 38 digits |
| Memory Usage | 8 bytes (fixed) | Variable (up to 16 bytes) |
| Rounding Errors | May introduce small differences | Minimized |
| Numeric Range | ~4.9e-324 to 1.8e+308 | Limited to 38 digits total |
| Suitable for | Scientific, engineering, analytics | Financial, currency, tax, invoices |
| Salesforce Recommendation | For scientific calculations | ✅ Recommended for financial data |
| Performance | Faster (hardware optimized) | Slower (software-based precision) |
| Example | 9.81 (gravity) | 1500.75 (currency) |
Double vs Integer
| Feature | Double | Integer |
|---|---|---|
| Stores decimal values | ✅ Yes | ❌ No (whole numbers only) |
| Arithmetic Type | Floating-point | Integer arithmetic |
| Memory Usage | 8 bytes | 4 bytes |
| Numeric Range | Very large (~4.9e-324 to 1.8e+308) | Limited (-2.1e9 to 2.1e9) |
| Suitable for | Scientific calculations | Counting and numbering |
| Example | 9.81 | 9 |
Common Double Methods
Apex provides several useful methods for working with Double values:
Double number = 123.4567;
// Convert to String
String str = String.valueOf(number);
System.debug('String: ' + str); // "123.4567"
// Format with specific decimal places
String formatted = String.format('{0,number,#.##}', new List<object>{number});
System.debug('Formatted: ' + formatted); // "123.46"
// Parse from String
Double parsed = Double.valueOf("999.99");
System.debug('Parsed: ' + parsed); // 999.99
// Check for special values
Double infinite = Double.valueOf('Infinity');
Double nan = Double.valueOf('NaN');
// Check if value is null
if (number != null) {
System.debug('Number is not null');
}
// Compare two doubles (with tolerance for floating-point errors)
Double a = 0.1 + 0.2;
Double b = 0.3;
Double tolerance = 0.0000001;
Boolean isEqual = Math.abs(a - b) < tolerance; // true (with tolerance)
Output
String: 123.4567 Formatted: 123.46 Parsed: 999.99 Number is not null
Common Double Pitfalls & Solutions
| Pitfall | Example | Solution |
|---|---|---|
| Null Pointer Exception | Double x; Double y = x + 5.0; |
Always initialize: Double x = 0.0; or check for null |
| Floating-Point Precision | 0.1 + 0.2 == 0.3 // false |
Use tolerance: Math.abs(a - b) < 0.000001 or use Decimal |
| Using Double for Currency | Double price = 99.99; |
Always use Decimal for currency: Decimal price = 99.99; |
| Division by Zero | Double result = 10.0 / 0.0; |
Check for zero before division: if (denominator != 0) |
| Comparing NaN or Infinity | if (value == Double.valueOf('NaN')) |
Use Double.isNaN() and Double.isInfinite() |
| Precision Loss in Financial Reporting | Double total = 1.05 - 0.42; |
Use Decimal instead of Double for financial reports |
How Salesforce Stores Double Values
Developer Writes
Double pi = 3.14159;
│
▼
Compiler Checks
✔ Double Type exists?
✔ Variable name valid?
✔ Floating-Point value compatible?
│
▼
Memory Allocated
64-bit (8 Bytes)
│
▼
Binary Representation (IEEE 754)
0 10000000000 10010010000111111011011...
│
▼
Available for Mathematical Operations
Used in formulas and scientific calculations
Double stores values in binary format using IEEE 754 standard, which can cause small rounding differences.
Common Salesforce Use Cases
| Business Requirement | Example Value | Use Case |
|---|---|---|
| Scientific Measurements | 36.75 | Temperature readings |
| Engineering Calculations | 9.81 | Gravity constant |
| GPS Coordinates | 28.6139 | Latitude & Longitude |
| Performance Analytics | 125.50 | Average response time (ms) |
| Statistical Reporting | 15.75 | Calculated metrics |
| Mathematical Constants | 3.14159265358979 | Pi, e, square roots |
| Survey Results | 4.5 | Average rating |
| Distance Calculations | 1150.45 | Distance in kilometers |
🔍 Behind the Scenes: Double Processing
Scientific Formula Input
│
▼
Floating-Point Calculation
Using binary arithmetic
│
▼
Approximate Precision Result
May have small rounding errors
│
▼
Result Returned
Used in analytics or reporting
✅ Best Practices
- Use Double for scientific and engineering calculations where approximate precision is acceptable.
- Use Decimal instead of Double for currency, tax, discounts, and financial values.
- Choose descriptive variable names such as
averageSpeed,earthRadius, orgravityConstant. - Understand that floating-point arithmetic may introduce tiny rounding differences.
- Use
Math.abs(a - b) < tolerancewhen comparing Double values for equality. - Always check for division by zero before performing division operations.
- Use scientific notation (
1.5e-10) for very small or very large values. - Initialize Double variables to avoid null pointer exceptions.
⚠️ Common Mistakes
- Using Double for Opportunity Amount or Invoice calculations (use Decimal instead).
- Expecting floating-point calculations to always produce exact decimal values.
- Confusing Double with Decimal because both support decimal numbers.
- Directly comparing Double values using
==without tolerance. - Forgetting that uninitialized Doubles are
null, not 0.0. - Using Double when Decimal precision is needed for business accuracy.
- Not handling Infinity or NaN values in calculations.
🎯 Interview Tip
Question: What is the primary difference between Double and Decimal in Apex?
Answer: Double uses floating-point arithmetic with approximately 15-16 digits of precision and is suitable for scientific or analytical calculations where approximate precision is acceptable. Decimal provides high-precision (up to 38 digits) exact decimal arithmetic and is the recommended choice for financial calculations such as Opportunity Amounts, Discounts, Taxes, Quotes, and Invoices.
Question: Why does 0.1 + 0.2 not equal 0.3 in Double?
Answer: This is due to the binary floating-point representation. In binary, 0.1 and 0.2 cannot be represented exactly, causing a small precision error. For example, 0.1 + 0.2 results in 0.30000000000000004 instead of 0.3. This is why Decimal is recommended for financial calculations where exact precision is required.
Question: When would you choose Double over Decimal?
Answer: Choose Double when working with very large or very small numbers (e.g., scientific constants like 6.022e23), performing complex mathematical operations (trigonometry, logarithms), when performance is critical, or when the calculation's precision requirements are not strict (e.g., analytical reports, statistical analysis).
📌 Quick Revision
- ✔ Stores floating-point decimal values (64-bit).
- ✔ Suitable for scientific, engineering, and analytical calculations.
- ✔ Supports a very large numeric range (~4.9e-324 to 1.8e+308).
- ✔ May introduce small floating-point rounding differences.
- ✔ Not recommended for financial calculations (use Decimal instead).
- ✔ Uses IEEE 754 double-precision format.
- ✔ Supports scientific notation (e.g.,
1.5e-10). - ✔ Common methods:
Double.valueOf(),Mathclass functions. - ✔ Use tolerance when comparing Double values for equality.
- ✔ Uninitialized Double variables default to
null.
➡ Next Lesson
In the next lesson, you'll explore the Long data type in detail. You'll learn:
- How Apex stores very large whole numbers.
- The numeric range of Long and when to use it.
- When to use Long instead of Integer for large values.
- Common use cases and best practices for Long.
- Understanding the differences between Integer, Long, and Decimal.
Practice What You've Learned
Test your understanding with these practice exercises