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.
- In the Salesforce developer console, first create an Apex class. Select File > New > Apex Class.
- Enter the name of a new apex class and click the OK button.
- 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.
- After saving the apex code, if there are no errors, press “Ctrl+E” to execute the code.
- 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);

- In the console log, select the option Debug only. Now, you will see the string formatted in a decimal data type.

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
- In the Salesforce developer console, first create an Apex class. Select File > New > Apex Class.
- Enter the name of a new apex class and click the OK button.
- 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));