From Database to Apex: Why Currency Values Look Different ?

Published by

on

While working with Currency fields in Salesforce, an unusual behavior was noticed. A value that appears as 1200 at the object level is appearing as 1199.9999999999999999999999999999994 when accessed through Apex.

It happens because, Salesforce handles the Currency fields in a different way.

How Salesforce Processes Currency Values

A Currency field in Salesforce is stored as a Decimal value with defined precision and scale. At the object level, Salesforce ensures the value is stored and displayed in a properly rounded format. So in the database, the value is stored as 1200.

But However, when this value is accessed from Apex, It goes in the following flow:

Salesforce Database → SOQL Query Engine → Apex Runtime Memory (Decimal variable)

Now we are not just referring to the field directly, It reads the value which is loaded into the memory. While reading from the memory, Salesforce converts the stored numerical value into a Decimal Object with high precision in Apex runtime memory. Due to which the value is appearing as 1199.9999999999999999999999999999994

This happens due to floating point precision differences that occur when numbers are represented in computer memory. The value is still the same logically, but the internal binary representation can introduce decimal variations.


Why This Appears in Debug Logs

When using System.debug(), Salesforce refers the numerical value present in memory rather than the formatted currency value. Because of this, the internal representation becomes visible in logs.

Even though the debug output shows a long decimal number, the actual stored value in Salesforce remains correctly rounded.


Observations in SOQL

This precision behavior will also affect SOQL equality filters.

For example, A query like

SELECT Id, Insurance_Premium_Amount__c
FROM Loan_Assets__c
WHERE Insurance_Premium_Amount__c = 1200

will return no records, even if the field is holding the value as 1200.

However, querying with the internal precision value:

SELECT Id, Insurance_Premium_Amount__c
FROM Loan_Assets__c
WHERE Insurance_Premium_Amount__c = 1199.9999999999999999999999999999994

will return the record. This occurs because the comparison is being made against the exact numeric value represented internally in memory.

Conclusion

This behavior is not a data issue but a result of how decimal numbers are represented internally in runtime memory. Salesforce stores the value correctly in the object leve and displays it in a rounded format. But when the value is processed in Apex, the floating-point precision differences will appear in debug logs.

Leave a comment