Imagine your sales team imports leads from a CSV file every morning. The file comes from different partners, and fields such as Annual Revenue, Discount Percentage, and Probability are stored as text.
You want to run accurate forecasts, build Sales dashboards, and automate follow‑up emails, but you can’t do that if all your numbers live in String fields instead of real numbers.
In Salesforce Apex, a String is just plain text, and a Double is a 64‑bit number that can store decimal values, like 1200000.75 or 0.15. Y
ou use Double when you need to work with numeric data that has decimal points, such as revenue, conversion rates, or product quantities with fractions.
If your CRM stores these values as text, you first need to convert them to Double so Apex can calculate, compare, and report correctly.
In Salesforce Apex, developers often work with different data types such as String, Integer, and Double. Sometimes we receive numeric values as strings and need to convert them to a double to perform calculations.
In our Salesforce org, the development team created a Lightning component that allows sales representatives to enter sales figures for their transactions. The user inputs the sales amount as a string.
I had to convert the string input to a double so that calculations, such as total sales and commissions, and report generation could be performed.
In this article, you will learn how to convert String to Double in Salesforce Apex with simple examples, real-time use cases, common errors, and best practices.
What is String and Double in Apex?
Before conversion, let’s understand both data types.
String in Apex
A String is a sequence of characters enclosed in single quotes.
String Name = 'John';
String email = 'john.doe@example.com';
String message = 'Hello, this is a test message!';
String price = '100.50';Double in Apex
Double is a numeric data type used to store decimal values.
Double price = 100.50;Why Convert a String to a Double in Apex?
We convert a String to a Double when:
- Data comes from UI (Text fields)
- Data comes from the API
- Values are stored as text but used in calculations
For example, you receive a price as “500.75” → need to calculate tax.
Convert String to Double in Salesforce Apex
Below, let’s explore different methods for converting a string to a double.
Example 1: Use Double.valueOf in Apex Code
Use this method when you’re writing Apex logic (triggers, classes, or batch jobs), and you already have a String value in hand. It’s the most direct way to turn text like “1200000.75” into a Double you can use in calculations.
To convert a string to a double in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.
In the steps below, we will convert the string to a double using the Double.valueOf(strValue) method in an Apex class.
- In the developer console, create a new Apex class from File > New > Apex Class. Then, enter the code below in the Apex class.
public class StringtoDouble {
public static void convertStringToDouble(String strValue) {
try {
Double doubleValue = Double.valueOf(strValue);
System.debug('Converted Double Value: ' + doubleValue);
} catch (System.TypeException e) {
System.debug('Invalid input: ' + strValue + ' cannot be converted to Double.');
}
}
}In the above code, we have used Double.valueOf(strValue); method to convert the string to a double, and we have also used the try-catch method to handle errors and invalid values.
- If there are no errors (problems) in the above code, then launch the anonymous apex window. After this, enter the code below into the anonymous window to debug the apex class, then click Execute.
StringToDouble.convertStringToDouble('453.50');
StringToDouble.convertStringToDouble('apex'); // Invalid conversion- In the execution log window, select the “debug only” checkbox. Then, you will see the value converted from a string to a Long data type in the output.

For invalid values, the output will display an error message for invalid strings or double values.
How does this work?
The Double.valueOf method reads the String and interprets it as a signed decimal number, then returns a Double value you can store in a variable or use in calculations. Apex treats “1200000.75” as a numeric value, which lets you sum, average, or compare it with other numbers.
This way, we can convert a string to a Double type in Salesforce Apex by using the valueOf(strValue) method.
Pro Tip: Always make sure the String is in a valid decimal format (only digits, optional sign, and a dot for decimals) before calling Double.valueOf, or Apex will throw a runtime exception.
Example 2: Product Price Calculation with Tax
In a real Salesforce project, product price often comes from:
- External system (API)
- CSV upload
- UI input field
Most of the time, the value is received as a String, but we need it as a Double to perform calculations such as taxes, discounts, or the total amount.
String priceStr = '1000.50';
// Convert String to Double
Double price = Double.valueOf(priceStr);
// Calculate 18% tax
Double tax = price * 0.18;
// Final amount
Double totalAmount = price + tax;
// Debug output
System.debug('Price: ' + price);
System.debug('Tax: ' + tax);
System.debug('Total Amount: ' + totalAmount);Output:
Price: 1000.5
Tax: 180.09
Total Amount: 1180.59Example 3: Processing Data from an External API
When Salesforce integrates with external systems (like payment gateways or ERP systems), numeric values are often returned as Strings.
Example API Response:
{
"amount": "250.75"
}Here we need to follow the logic:
- Extract amount from API response
- Convert String to Double
- Use it in calculations or store it in records
String apiAmount = '250.75';
// Convert to Double
Double amount = Double.valueOf(apiAmount);
// Apply discount (10%)
Double discount = amount * 0.10;
Double finalAmount = amount - discount;
System.debug('Original Amount: ' + amount);
System.debug('Discount: ' + discount);
System.debug('Final Amount: ' + finalAmount);Output:
Original Amount: 250.75
Discount: 25.075
Final Amount: 225.675Example 4: User Input from Screen Flow or UI
In Salesforce Screen Flow or Lightning Component:
- User enters an amount in a Text field
- That value is passed to Apex as a String
Here we need to follow the logic:
- Get user input
- Convert to Double
- Perform validation or calculation
String userInput = '500.25';
// Convert to Double
Double amount = Double.valueOf(userInput);
// Apply validation
if(amount > 1000){
System.debug('High Value Transaction');
} else {
System.debug('Normal Transaction');
}Output:
Normal TransactionExample 5: Bulk Data Processing (List of Records)
You receive multiple values (CSV, batch job, data migration), and some values may be invalid.
Here we need to follow the logic:
- Loop through the list of Strings
- Convert each value
- Handle errors using try-catch
- Store only valid values
List<String> priceList = new List<String>{'100.5', '200.75', 'ABC', '300.25'};
List<Double> validPrices = new List<Double>();
for(String value : priceList){
try {
Double price = Double.valueOf(value);
validPrices.add(price);
} catch(Exception e){
System.debug('Invalid value skipped: ' + value);
}
}
System.debug('Valid Prices: ' + validPrices);Output:
Invalid value skipped: ABC
Valid Prices: (100.5, 200.75, 300.25)Things to Keep in Mind
- Validate input format first
Always verify that String values contain only digits, an optional sign, and a decimal point before conversion to avoid NumberFormatException at runtime. - Watch Apex governor limits
Bulkify triggers and Batch Apex so you don’t perform heavy conversion logic per record without using efficient loops and avoiding unnecessary debug logs. - Handle nulls and blanks
Treat blank or null strings as null doubles, and decide whether to default to zero based on your reporting rules to avoid misleading totals. - Check field types in Object Manager
If you need decimals, use Number fields with sufficient Decimal Places instead of Text fields, or you’ll keep converting on the fly, which complicates reporting. - Use sandbox for testing
- Always deploy new triggers and Apex classes from sandbox to production after writing unit tests that cover both valid and invalid numeric strings.
- Align with Salesforce editions
- Some automation features, such as Record‑Triggered Flows and advanced Apex, may behave differently across the Essentials, Professional, and Enterprise editions, so check availability before designing solutions.
Conclusion
You learned four practical ways to convert a string to a double in Salesforce Apex, from simple Double.valueOf calls to safe parsing in triggers and Flows.
Use direct conversion in clean data scenarios, safe parsing for imports and integrations, triggers for field syncing, and invocable Apex for admin‑friendly Flows. I hope you found this article helpful.
Converting a string to a double in Salesforce Apex is a simple but important concept. It is widely used in real-world scenarios like calculations, integrations, and user input processing.
By using Double.valueOf() along with proper validation and error handling, you can ensure your code works efficiently and avoids runtime errors.
You may also like to read.
- Convert String to Datetime in Salesforce Apex
- Convert String to Blob in Salesforce Apex
- Convert a String to Decimal in Salesforce Apex
- Convert String to Boolean in Salesforce Apex
- Convert String to ID in Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.