[SalesForce] How to set the value of a currency field from a formatted string

In apex, how would you set the value of a currency field with a formatted string? See the sample code:

String price = '$1,000.00';

MyObj__c obj = new MyObj__c();

// this line won't compile, so I've commented it out:
// obj.price__c = price;

// this line would generate a runtime error: 'Invalid Decimal'
obj.price__c = Decimal.valueOf(price);

However, on a standard layout, you can use dollar signs, commas, decimals, etc. with no problem. One approach is to strip the dollar signs and commas. This would work for US currency but not for all currencies, which would apply in multi currency orgs. Would you have to write a function to look at the user's currency setting and strip the invalid characters?

By the way, the string value is getting passed in via javascript, so it is not done through visualforce databinding.

Best Answer

I did something like below : \p{sc} is the REGEX that matches all the currency

string i= '₪10,000';
Pattern dollarPattern = Pattern.compile('[\\p{Sc},]');
string s = dollarPattern.matcher(i).replaceAll('');
decimal d = decimal.valueof(s);
system.debug('####'+d);

I tried this with £,¥,₪ and $ and got 10000 as consistent output.

I looked at this post and got an idea on the Regex for currency : https://stackoverflow.com/questions/14169820/regular-expression-to-match-all-currency-symbols

Using pattern matcher I replaced all with ''.

To test with multiple currencies use http://currencies.typeit.org/ if you did not know how to type the currencies like me.

UPDATE:

Do you think this works ?

string i= '₪100,000,003';
if(i.contains(',')){
    i= i.replaceall(',','');}
Pattern dollarPattern = Pattern.compile('[\\p{Sc}]');
string s = dollarPattern.matcher(i).replaceAll('');
decimal d = decimal.valueof(s);
System.debug('####'+d);

Hope this helps.

Related Topic