[SalesForce] Convert a String to a Decimal

in my code I need to put a String contained inside a map in a Decimal variable. Now I have 2 problems, the first one is the format of the String because it can contain ' , ' and ' . ' e.g. '21,31' or '3.124,23', the second one is that when I use Decimal.ValueOF(string) method System gives me "invalid decimal error" despite my code.
Here my code:

[...]
if(fieldMapped.contains('UnitPrice')){   
System.debug(mapFieldColumn.get('UnitPrice')[t].right(4));
//controll over price format
if(mapFieldColumn.get('UnitPrice')[t]!=''){    
   if((mapFieldColumn.get('UnitPrice')[t].right(4)).contains('.')){               
      mapFieldColumn.get('UnitPrice')[t]=mapFieldColumn.get('UnitPrice')[t].remove(',');
   }else if((mapFieldColumn.get('UnitPrice')[t].right(4)).contains(',')){
      mapFieldColumn.get('UnitPrice')[t]=mapFieldColumn.get('UnitPrice')[t].remove('.').replace(',','.');                     
   }else{
      mapFieldColumn.get('UnitPrice')[t]='0';
   }
   oli.UnitPrice = Decimal.ValueOf(mapFieldColumn.get('UnitPrice')[t]);
   }
}       
[...]

The system debug shows the error:
"Exception: System.TypeException: Invalid decimal: € 28836.81 ".
The String I was trying to cast is = "2.8836,81"

Best Answer

Consider using a regular expression and the replaceAll() method.

The following expression will identify any character that is not a decimal point or a digit. You can try it out at regex101.com

[^.\d]

In Apex you'll need to escape the slash...

[^.\\d]

By this you'll be able to strip out the comma without having to go searching for it.

String value = '12,345.678';
system.assertEquals('12345.678', value.replaceAll('[^.\\d]','');
system.assertEquals(12345.678, Decimal.valueOf(value.replaceAll('[^.\\d]',''));

This cleaned-up value should convert to a Decimal without giving an error. You may also find it helpful to create a utility method that takes the String to be converted as well as a Decimal value to return if an error occurs.

Related Topic