+ Start a Discussion
Ken Koellner 7Ken Koellner 7 

There is no method to parse a string decimal to decimal [opposite of Decimal.format()]

SF documentation says to use methods that support Locale, specfically format().  But I'm sorely disappointed to find there there is no inverse of this method.  valueOf() is not the inverse of format(). 

Decimal myDecimal = 123456.09;
String myString = myDecimal.format();
Gives me "123,456.09" in the US.

If you call Decimal.valueOf('123,456.09') you get an exception.  And if you had your locale set to France, you'd get the analogous error with Decimal.valueOf('123.456,09').

It appears I now have to write a method that understands Locale and the characters used in that Local and approrpriately hacks the value to get valueOf() to work.  

Before I write it, anyone have such a method already coded?

 

(It really seems to be that Apex should be able to do this out of the box.)

Ken Koellner 7Ken Koellner 7

I'm going to try something like the below for now.  This is the type of thing that keeps me up at night.  I tested in English US, English Canada, French Canada, and French France.  But is there some weird locale that could break it at some point?  I do not understand why SF does not deliver Locale-specific parsing methods for Decimal, Double when they do for Datetime.  Did just miss them in the documentation?

public Decimal parseDecimal(String myDecimalString) {
  if (String.isBlank(myDecimalString) == null) {
    return null;
  }
  Decimal sampleDecimal=1.1;
  String decimalPoint=sampleDecimal.format().replaceAll('[^.,]','');
  System.debug(decimalPoint);
  String replaceString = '[^0-9' + decimalPoint + ']';
  String tempString = myDecimalString.replaceAll(replaceString,'');
  tempString = tempString.replace(',','.');
  return Decimal.valueOf(tempString);
}

Decimal inDecimal = 123456.09;
String inDecimalString = inDecimal.format();
System.debug ('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ' + parseDecimal(inDecimalString));