0

I need help on storing currency fields with their currencyisocode while working with triggers

for(sObject o : newRecordsFromTrigger){  
    Capture_Field_History__c fh = new Capture_Field_History__c();
    fh.NewValue__c = String.valueOf(o.get(fieldName)); // output is 100.00
    fh.OldValue__c = String.valueOf(oldObject.get(fieldName)); // output is 50.00
    list.add(fh);
}

In above code if the trigger is firing from Opportunity having Amount changed from 50.00 to 100.00 and fieldName is Amount then I will have 100.00 in NewValue instead I want it to be stored as ISO_CODEvalue i.e. USD 100.00 .

I tried using below code to format but it didn't work :-

fh.NewValue__c = String.valueOf(((Decimal)(o.get(fieldName))).format()); // output is 100

I know we can achieve it using SOQL as below but in this case of triggers I am avoiding using SOQL

Opportunity opp = [SELECT Id, format(Amount) amt FROM Opportunity LIMIT 1] // opp.get('amt') = USD 100.00
2
  • Have you tried o.get('CurrencyIsoCode') in your loop?
    – TSmith
    Oct 7, 2021 at 11:44
  • That will give me the Iso Code i.e. USD for eg but will not format the currency field i.e. USD 100.00. Oct 7, 2021 at 12:04

1 Answer 1

1

I think you can combine fetching the CurrencyIsoCode with a different way of converting the field value to a String. E.g.

fh.NewValue__c = o.get('CurrencyIsoCode') + ' ' + String.valueOf(o.get('sfims__Amount__c'))

However, displaying the Decimal as a formatted String has some complex aspects to it which have been discussed in detail on sf stackexchange in the past. E.g. this question has some excellent more advanced solutions: What is a concise function that formats a (String) decimal into a currency format in Apex?

That would e.g. result in

private String formatCurrency(Decimal i) {
    if (i == null) return '0.00';
    i = Decimal.valueOf(Math.roundToLong(i * 100)) / 100;
    String s = (i.setScale(2) + (i >= 0 ? 0.001 : -0.001)).format();
    return s.substring(0, s.length() - 1);
}

and

fh.NewValue__c = o.get('CurrencyIsoCode') + ' ' + formatCurrency(o.get('sfims__Amount__c'))

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .