Convert String to Double in Salesforce Apex (With Examples & Real Use Cases)

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

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 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

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.

  1. 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 double, and we have also used the try-catch method to handle the errors and invalid values.

  1. If there are no errors (problems) in the above code, then launch the anonymous apex window. After this, enter the code below in the anonymous window to debug the apex class and click Execute.
StringToDouble.convertStringToDouble('453.50'); 
StringToDouble.convertStringToDouble('apex');    // Invalid conversion
  1. In the execution log window, select the debug only” checkbox. Then, you will see the value converted from a string to a Long date type in the output.
Convert String to Double in Salesforce Apex

For invalid values, the output will display an error message for invalid strings or double values.

This way, we can convert a string to a Double type in Salesforce Apex by using the valueOf(strValue) method.

Example 1: 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.59

Example 2: Processing Data from an External API

When Salesforce integrates with external systems (like payment gateways or ERP systems), numeric values are often returned as String.

Example API Response:

{
  "amount": "250.75"
}

Here we need to follow the logic:

  1. Extract amount from API response
  2. Convert String to Double
  3. 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.675

Example 3: 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 String

Here we need to follow the logic:

  1. Get user input
  2. Convert to Double
  3. 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 Transaction

Example 4: 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:

  1. Loop through the list of Strings
  2. Convert each value
  3. Handle errors using try-catch
  4. 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)

Conclusion

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.

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.