Convert a String to Decimal in Salesforce Apex

While working as a Salesforce developer, I recently fixed an issue related to the input product pricing field data type. In the Salesforce application, there was a lightning component where the user could enter the product price, and by default, the input field was a string.

To perform calculations with the entered value, such as applying taxes or discounts, the field data must be in decimal format.

In this Salesforce tutorial, I will explain how to convert a string to a decimal in Salesforce Apex.

Convert a String to Decimal in Salesforce Apex

To convert a string to a decimal object in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.

  1. In the Salesforce developer console, first create an Apex class. Select File > New > Apex Class.
  1. Enter the name of a new apex class and click the OK button.
  1. Enter the code below in the developer console and save it.
public class ConvertStringtoDecimal {
    
    public static Decimal convertStringToDecimal(String strNumber) {
        return Decimal.valueOf(strNumber);
    }
}

In the above apex public class, we have used the Decimal.valueOf(strNumber) method, which converts the input string strNumber into a Decimal value using the Decimal.valueOf() method.

  1. After saving the apex code, if there are no errors, press “Ctrl+E” to execute the code.
  1. In the anonymous window, enter the code below, select “Open in Log,” and press the Execute button.
String strNumber = '456.80';
Decimal decimalNumber = ConvertStringtoDecimal.convertStringToDecimal(strNumber);
System.debug('Converted Decimal: ' + decimalNumber);
Salesforce apex Convert string to decimal
  1. In the console log, select the option Debug only. Now, you will see the string formatted in a decimal data type.
Convert a list of string to a list of decimal in apex

Following the above steps, we can convert string data to a decimal in Salesforce Apex.

Convert List of Strings to List of Decimals in Salesforce Apex

  1. In the Salesforce developer console, first create an Apex class. Select File > New > Apex Class.
  1. Enter the name of a new apex class and click the OK button.
  1. Enter the code below in the developer console and save it.
public class ListofStringtoDecimal {
    public static void convertList() {
        List<String> stringList = new List<String>{'1.23','4.56','7.89','10.11'};
        List<Decimal> decimalList = new List<Decimal>();
        
        for (String str : stringList) {
            decimalList.add(Decimal.valueOf(str));