[SalesForce] Invalid Decimal – Visualforce error. Am using Decimal.valueOf(string);

This is my method:

public static String getSumInfo() {
    String x = ChartController.getNewBusinessClosedWonJanuary(); 
    String y = ChartController.getNewBusinessClosedWonFebruary();
    Decimal x1 = Decimal.valueOf(x);
    Decimal y1 = Decimal.valueOf(y);
    Decimal num = (x1 + y1);
    if (num == null) {
        num = 0;  
    }
    return JSON.serialize(num);
}   

When I refresh the VF page, the error: 'Invalid decimal: [89716]' appears.

Best Answer

As far as I can tell, your methods getNewBusinessClosedWonJanuary and getNewBusinessClosedWonFebruary are returning excess data with the string. You'll have to filter these down to just the numbers you need for your class.

Adding a short method to filter them, and two calls to that method, would likely be a decent short-term solution, if you aren't able to modify the methods you are using in your class.

This snippet below uses regex based off this question as an example for this case. You could also use '[^0-9]', but this would cause any periods to be removed, potentially modifying your decimals.

public static String SanitizeInput(String s) {
    Pattern numeric = Pattern.compile('(\d)?\.(\d)+');
    Matcher matcher = numeric.matcher(s);

    return matcher.find() ? matcher.group() : '';
}

And add a call to the newly created method in your controller. You'll need to add a check against the x and y values being '', since calling Double.valueOf(''); gives an exception.

public static String getSumInfo() {
    String x = Controller.SanitizeInput(ChartController.getNewBusinessClosedWonJanuary()); 
    String y = Controller.SanitizeInput(ChartController.getNewBusinessClosedWonFebruary());
    Decimal x1 = Decimal.valueOf(x);
    Decimal y1 = Decimal.valueOf(y);
    Decimal num = (x1 + y1);
    if (num == null) {
        num = 0;  
    }
    return JSON.serialize(num);
}   
Related Topic