I am looping on a list of sObejct records and need to format the fields which are for CURRENCY data type to correct format. I know we have format() function for it but the challenge I am facing is to apply it when we are getting value dynamically from a sObject i.e.

AnnualContractCalue__c is a CURRENCY field

sObject obj = [SELECT Id, AnnualContractCalue__c FROM Opportunity where Id = 'xyz'];

system.debug('ACV = '+opp.AnnualContractCalue__c);
system.debug('ACV format = '+opp.annualcontractvalue__c.format()); // It is working fine here 
system.debug('ACV format dynamically = '+opp.get('annualcontractvalue__c').format()); // getting error 

Output :-

ACV = 449.999999999999999

ACV format = 450

1 Answer 1


The sObject.get(field) method returns an Object, so the compiler doesn't know what type the data is at compile-time (it can't even know if the field is valid or not!). So, you have to help the compiler along by telling it what type of data it's dealing with. We do this by using a "cast" or a "valueof" method:

// Cast from Object to Decimal
system.debug('ACV format dynamically = '+


// Decimal.valueOf accepts an Object and returns a Decimal
system.debug('ACV format dynamically = '+
  • @sfdxfox great its working.. one more thing - Is there a way to get the currency ISO code along with the currency value? Commented Sep 20, 2021 at 13:33
  • @arpitgupta that's in the CurrencyIsoCode field. The currency field itself contains a number amount.
    – sfdcfox
    Commented Sep 20, 2021 at 14:03
  • @sfdxfox Can you write a code for the same please. I see it is working while using format in SOQL i.e. SELECT Id, format(annualcontractvalue__c) acv from Opportunity - acv will have CurrencyIsoCode - but how to get the same output in apex without SOQL Commented Oct 7, 2021 at 9:34
  • @arpitgupta (Decimal)opp.get('annualcontractvalue__c')+' '+opp.CurrencyIsoCode
    – sfdcfox
    Commented Oct 7, 2021 at 12:50

You must log in to answer this question.

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