Decimal
Learning Content
Last updated: July 28, 2026
Decimal Data Type
The Decimal data type is used to store numbers containing decimal places with high precision. It is the preferred numeric type for financial calculations because it minimizes rounding errors that can occur with floating-point arithmetic.
In Salesforce, fields such as Opportunity Amount, Quote Total, Discount Percentage, Tax Amount, and Invoice Value are commonly represented using the Decimal data type.
💡 LearnFrenzy Insight
Imagine you're calculating the total bill in a supermarket. The bill might be:
- ₹125.50
- ₹899.99
- ₹15000.75
Money almost always contains decimal values. Using an Integer would remove the decimal portion, while Decimal preserves the exact value required for accurate financial calculations.
What is a Decimal?
A Decimal stores numeric values that contain fractional digits. Unlike Integer, it supports decimal places and provides greater precision for calculations involving money, percentages, measurements, and scientific values.
Decimal price = 499.99; Decimal tax = 18.50; Decimal discount = 5.25; Decimal zeroValue = 0.0; // Zero with decimal Decimal negativeValue = -99.99; // Negative decimal values are also supported
💡 Pro Tip: Decimal in Apex is a high-precision 38-digit number. It's actually a Salesforce wrapper around the Java java.math.BigDecimal class, which provides arbitrary precision.
Decimal Precision & Scale
A Decimal has two important characteristics:
| Property | Description | Example |
|---|---|---|
| Precision | Total number of digits (both sides of decimal point) | 12345.67 → Precision = 7 |
| Scale | Number of digits after the decimal point | 12345.67 → Scale = 2 |
⚠️ Important Note: Apex Decimal supports up to 38 digits of precision. This is sufficient for virtually all business and financial calculations.
Why Use Decimal?
| Reason | Benefit |
|---|---|
| High Precision | Stores decimal values accurately with up to 38 digits |
| Financial Calculations | Ideal for currency and accounting with exact decimal math |
| Percentage Calculations | Supports fractional percentage values like 5.5%, 12.75% |
| Business Applications | Used extensively throughout Salesforce for amounts, totals, and metrics |
| No Rounding Errors | Unlike Double, Decimal provides exact decimal arithmetic |
Variable Declaration & Initialization
You can declare and initialize Decimal variables in several ways:
// Method 1: Declaration with initialization Decimal salary = 45000.75; Decimal price = 125.99; // Method 2: Declaration without initialization (defaults to null) Decimal gstRate; gstRate = 18.00; // Initialization later // Method 3: Using the 'new' keyword Decimal amount = new Decimal(999.99); // Method 4: Multiple declarations (not recommended) Decimal a = 10.5, b = 20.75, c = 30.25; // Method 5: From Integer Integer count = 100; Decimal decimalFromInteger = Decimal.valueOf(count); // 100.0
📝 Key Points:
- Uninitialized Decimal variables default to
null, not 0.0. - Always initialize Decimal variables before use to avoid null pointer exceptions.
- Use descriptive names like
totalAmountinstead ofamt.
Basic Arithmetic Operations
Decimals support all standard arithmetic operations with high precision:
Decimal price = 1500.50;
Decimal tax = 250.25;
Decimal discount = 75.75;
Integer quantity = 3;
// Basic Arithmetic
System.debug('Addition: ' + (price + tax)); // 1750.75
System.debug('Subtraction: ' + (price - discount)); // 1424.75
System.debug('Multiplication: ' + (price * quantity)); // 4501.50
System.debug('Division: ' + (price / 2)); // 750.25
System.debug('Modulus: ' + (25 % 2)); // 1.0
// Compound operations
Decimal total = price + tax - discount; // 1675.00
System.debug('Total after tax and discount: ' + total);
Output
Addition: 1750.75 Subtraction: 1424.75 Multiplication: 4501.50 Division: 750.25 Modulus: 1.0 Total after tax and discount: 1675.00
Decimal Formatting & Rounding
Apex provides several methods to format and round Decimal values:
Decimal amount = 1234.5678;
// Format to String
String formatted = amount.format(); // "1,234.568"
// Round to specific decimal places
Decimal rounded1 = amount.setScale(2); // 1234.57 (rounds half-up)
Decimal rounded2 = amount.setScale(0); // 1235 (rounds to nearest whole)
// Round with different rounding modes
Decimal roundedHalfUp = amount.setScale(2, System.RoundingMode.HALF_UP); // 1234.57
Decimal roundedHalfDown = amount.setScale(2, System.RoundingMode.HALF_DOWN); // 1234.57
Decimal roundedDown = amount.setScale(2, System.RoundingMode.DOWN); // 1234.56
Decimal roundedUp = amount.setScale(2, System.RoundingMode.UP); // 1234.57
// Currency formatting
String currencyFormatted = Decimal.valueOf(1500.50).format();
System.debug('Currency: $' + currencyFormatted); // Currency: $1,500.50
// Percentage formatting
Decimal percentValue = 0.75;
String percentStr = (percentValue * 100).format() + '%';
System.debug(percentStr); // 75%
Output
Formatted: 1,234.568 Rounded (2 decimals): 1234.57 Rounded (0 decimals): 1235 Currency: $1,500.50 75%
💡 Pro Tip: Always use setScale() with appropriate RoundingMode for financial calculations to maintain consistency.
Real Salesforce Business Example
🏢 Business Scenario 1: Opportunity Discount Calculation
A company offers a 15% discount on an Opportunity worth ₹25,000 with an additional 5% tax on the discounted amount.
Decimal opportunityAmount = 25000.00;
Decimal discountPercent = 15.00;
Decimal taxPercent = 5.00;
// Calculate discount
Decimal discount = (opportunityAmount * discountPercent) / 100;
System.debug('Discount Amount: ₹' + discount); // ₹3750.00
// Calculate amount after discount
Decimal afterDiscount = opportunityAmount - discount;
System.debug('After Discount: ₹' + afterDiscount); // ₹21250.00
// Calculate tax
Decimal tax = (afterDiscount * taxPercent) / 100;
System.debug('Tax Amount: ₹' + tax); // ₹1062.50
// Calculate final amount
Decimal finalAmount = afterDiscount + tax;
System.debug('Final Amount: ₹' + finalAmount); // ₹22312.50
Output
Discount Amount: ₹3750.00 After Discount: ₹21250.00 Tax Amount: ₹1062.50 Final Amount: ₹22312.50
🏢 Business Scenario 2: Employee Salary Calculation
Calculate monthly salary with basic pay, allowances, and deductions.
Decimal basicSalary = 50000.00;
Decimal hraPercent = 20.00; // House Rent Allowance
Decimal daPercent = 15.00; // Dearness Allowance
Decimal taxPercent = 10.00; // Tax deduction
Decimal professionalTax = 200.00;
// Calculate allowances
Decimal hra = (basicSalary * hraPercent) / 100;
Decimal da = (basicSalary * daPercent) / 100;
// Calculate gross salary
Decimal grossSalary = basicSalary + hra + da;
System.debug('Gross Salary: ₹' + grossSalary);
// Calculate tax deduction
Decimal tax = (grossSalary * taxPercent) / 100;
// Calculate net salary
Decimal netSalary = grossSalary - tax - professionalTax;
System.debug('Net Salary: ₹' + netSalary);
Output
Gross Salary: ₹67500.00 Net Salary: ₹60550.00
🏢 Business Scenario 3: Inventory Valuation
Calculate the total value of inventory with product quantities and unit prices.
// Product inventory data
Decimal product1Price = 1500.50;
Integer product1Qty = 25;
Decimal product2Price = 750.25;
Integer product2Qty = 40;
Decimal product3Price = 299.99;
Integer product3Qty = 100;
// Calculate total value for each product
Decimal product1Value = product1Price * product1Qty;
Decimal product2Value = product2Price * product2Qty;
Decimal product3Value = product3Price * product3Qty;
// Calculate total inventory value
Decimal totalInventoryValue = product1Value + product2Value + product3Value;
System.debug('Product 1 Value: ₹' + product1Value); // ₹37512.50
System.debug('Product 2 Value: ₹' + product2Value); // ₹30010.00
System.debug('Product 3 Value: ₹' + product3Value); // ₹29999.00
System.debug('Total Inventory Value: ₹' + totalInventoryValue); // ₹97521.50
Common Decimal Operations
| Operator/Method | Description | Example | Result |
|---|---|---|---|
+ | Addition | 1500.50 + 250.25 | 1750.75 |
- | Subtraction | 1500.50 - 75.75 | 1424.75 |
* | Multiplication | 1500.50 * 3 | 4501.50 |
/ | Division | 1500.50 / 2 | 750.25 |
% | Modulus | 25.5 % 2 | 1.5 |
setScale() | Round to decimal places | 123.456.setScale(2) | 123.46 |
format() | Format as string | 1234.50.format() | "1,234.50" |
valueOf() | Convert to Decimal | Decimal.valueOf("1500.75") | 1500.75 |
Decimal vs Integer
| Feature | Decimal | Integer |
|---|---|---|
| Supports decimal values | ✅ Yes | ❌ No (whole numbers only) |
| Precision | High (up to 38 digits) | Limited (32-bit) |
| Memory Usage | Variable (up to 16 bytes) | 4 bytes fixed |
| Ideal for | Money, percentages, measurements | Counting, indexing, IDs |
| Default value | null | null |
| Example | 1500.75 | 1500 |
| Rounding errors | Minimal | N/A (no decimals) |
Decimal vs Double
| Feature | Decimal | Double |
|---|---|---|
| Precision | High (exact decimal math) | Floating-point (approximate) |
| Memory Usage | Variable (up to 16 bytes) | 8 bytes fixed |
| Rounding Errors | Minimized | Can cause floating-point errors |
| Preferred for | Currency, financial data | Scientific calculations |
| Salesforce Recommendation | ✅ Recommended for financial data | ⚠️ Not recommended for money |
| Performance | Slower (due to precision) | Faster |
| Example | 1500.50 | 3.1415926535 |
Common Decimal Methods
Apex provides several useful methods for working with Decimal values:
Decimal number = 1234.5678;
// Rounding methods
Decimal rounded = number.round(System.RoundingMode.HALF_UP);
System.debug('Rounded: ' + rounded); // 1235
// Set scale
Decimal scaled = number.setScale(2);
System.debug('Scaled: ' + scaled); // 1234.57
// Convert to String
String str = number.format();
System.debug('Formatted: ' + str); // 1,234.568
// Parse from String
Decimal parsed = Decimal.valueOf("999.99");
System.debug('Parsed: ' + parsed); // 999.99
// Check if value is null
if (number != null) {
System.debug('Number is not null');
}
// Compare two decimals
Decimal a = 100.50;
Decimal b = 100.50;
Boolean isEqual = a == b; // true
Integer compareResult = a.compareTo(b); // 0 if equal
// Get scale and precision (advanced)
Integer scale = number.scale(); // 4 (number of decimal places)
Output
Rounded: 1235 Scaled: 1234.57 Formatted: 1,234.568 Parsed: 999.99
Common Decimal Pitfalls & Solutions
| Pitfall | Example | Solution |
|---|---|---|
| Null Pointer Exception | Decimal x; Decimal y = x + 5; |
Always initialize: Decimal x = 0.0; or check for null |
| Precision Loss in Division | Decimal result = 10 / 3; // Returns 3.0 |
Use decimal literals: Decimal result = 10.0 / 3; |
| Using Integer for Money | Integer price = 99.99; |
Always use Decimal for currency: Decimal price = 99.99; |
| Incorrect Rounding | value.setScale(2); // Default half-up |
Specify rounding mode: value.setScale(2, System.RoundingMode.HALF_UP); |
| Comparing Decimal with Integer | if (decimalVal == 100) |
Use same types: if (decimalVal == Decimal.valueOf(100)) |
How Salesforce Stores Decimal Values
Developer Writes
Decimal amount = 9999.95;
│
▼
Compiler Checks
✔ Decimal Type exists?
✔ Variable name valid?
✔ Numeric value compatible?
│
▼
Memory Allocated
Variable length based on precision needed
│
▼
High Precision Value Stored
9999.95 (exact decimal representation)
│
▼
Available for Calculations
Used in formulas, logic, and updates
Decimal uses BigDecimal internally for exact decimal arithmetic without floating-point errors.
Common Salesforce Use Cases
| Business Requirement | Example Value | Salesforce Object/Field |
|---|---|---|
| Opportunity Amount | 250000.50 | Opportunity.Amount |
| Invoice Total | 1500.75 | Invoice__c.Total__c |
| Tax Amount | 280.25 | Order.Tax_Amount__c |
| Discount Percentage | 15.50 | Quote.Discount__c |
| Commission Rate | 5.25 | User.Commission_Percent__c |
| Unit Price | 99.99 | Product2.UnitPrice |
| Exchange Rate | 83.45 | DatedConversionRate.ConversionRate |
| Salary | 75000.00 | Employee__c.Salary__c |
🔍 Behind the Scenes: Decimal Processing
Opportunity Amount (Decimal)
│
▼
Calculate Discount (Decimal)
Amount * Discount% / 100
│
▼
Apply Tax Calculation (Decimal)
Discounted Amount * Tax% / 100
│
▼
Rounding Applied (setScale)
Using HALF_UP rounding mode
│
▼
Final Amount Generated (Decimal)
Displayed to User with formatting
│
▼
Stored in Database
As Decimal field
✅ Best Practices
- Use Decimal for all financial calculations, currency, and precise measurements.
- Use meaningful variable names such as
totalAmount,discountPercent, ortaxValue. - Avoid using Double for currency fields - always prefer Decimal for money.
- Always specify rounding mode when using
setScale()for financial calculations. - Validate and test calculations before updating Salesforce records.
- Initialize Decimal variables to avoid null pointer exceptions.
- Use
Decimal.valueOf()for safe string to decimal conversions with error handling. - Store decimal values with appropriate precision (e.g., currency usually needs 2 decimal places).
⚠️ Common Mistakes
- Using Integer for currency values (e.g.,
Integer price = 99.99;). - Using Double for financial calculations (can introduce rounding errors).
- Ignoring decimal precision during calculations (unexpected results).
- Performing unnecessary type conversions that might lose precision.
- Forgetting to handle null values before arithmetic operations.
- Using default rounding when specific rounding mode is required for compliance.
- Assuming Decimal division always returns a Decimal (works but be careful with Integer division).
🎯 Interview Tip
Question: Why is Decimal preferred over Double for currency calculations in Apex?
Answer: Decimal provides exact decimal arithmetic and higher precision (up to 38 digits) while minimizing floating-point rounding errors. Double uses binary floating-point representation which can cause small rounding errors (like 0.1 + 0.2 = 0.30000000000000004). Salesforce specifically recommends using Decimal for financial values such as Opportunity Amount, Quotes, Discounts, Taxes, and Invoices because accuracy is critical in business applications.
Question: What is the difference between setScale() and round() in Apex?
Answer: setScale() is used to set the number of decimal places and can specify a rounding mode. round() is a simpler method that rounds to the nearest whole number. For financial calculations, setScale() with explicit rounding mode is preferred for precise control.
📌 Quick Revision
- ✔ Stores decimal numbers with high precision (up to 38 digits).
- ✔ Best choice for financial and currency calculations.
- ✔ Supports arithmetic operators (+, -, *, /, %).
- ✔ Uses
BigDecimalinternally for exact decimal arithmetic. - ✔ Common methods:
setScale(),format(),round(),valueOf(). - ✔ Commonly used for Opportunity Amount, Tax, Discount, and Invoice calculations.
- ✔ Preferred over Double when calculation accuracy matters.
- ✔ One of the most frequently used Apex data types in enterprise Salesforce applications.
- ✔ Always use
Decimal.valueOf()for safe string parsing. - ✔ Uninitialized Decimal variables default to
null.
➡ Next Lesson
In the next lesson, you'll explore the Double data type in detail. You'll learn:
- How floating-point numbers work and their limitations.
- When to use Double vs Decimal in Apex.
- Common use cases for Double in scientific calculations.
- Understanding floating-point precision issues and how to handle them.
Practice What You've Learned
Test your understanding with these practice exercises