# Math/Subtraction is different between Formula field and Apex

I have a Formula field which does simple subtraction between two other fields.

Field X - Formula (return type Number, 2 decimal places).

Field Y - Currency(16, 2)

The formula field simply does : `X - Y`. It is Currency return type,

I'm seeing differences in math when replicating what the Formula field does (simple subtraction in Apex).

When X and Y are both `-0.01`, the difference should be `0.00`

Formula Field computes to : `0.01`

Apex Subtraction computes to: `0.00`

The above values were printed using `System.debug`.

I know Currency's round "half-even" by default, but even when using `System.RoundingMode.HALF_EVEN` on both X and Y, the Apex calculation is still rightfully `0`.

Any help is appreciated!

``````// obj.X - Formula (Return type Number, 2 decimal places.)
// obj.Y - Currency (16,2) 16 length, 2 decimal places.
// obj.Z - Formula (Currency, 2 decimal places) - `X - Y`
System.debug(obj.X);            //X prints -0.01
System.debug(obj.Y);            //Y prints -0.01
System.debug('MANUAL MATH');
System.debug(obj.X - obj.Y);    //Apex math prints 0.00
System.debug('Formula field');
System.debug(obj.Z);            //Z prints 0.01
``````
• Can you share more of the Apex code you are using Nov 22 '19 at 20:42
• @BryanAnderson sure, I basically put what i was doing in anonymous apex. Nov 22 '19 at 20:48

So I am getting this (sorry I couldn't put this all in a comment):

``````test_Object__c obj = [Select xfld__c,yfld__c,zfld__c From test_Object__c WHERE Name = 'test'];

System.debug(obj.xfld__c);            //X prints -0.01
System.debug(obj.yfld__c);            //Y prints -0.01
System.debug('MANUAL MATH');
System.debug(obj.xfld__c - obj.yfld__c);    //Apex math prints 0.00
System.debug('Formula field');
System.debug(obj.zfld__c);
``````

Results: • I replicated this too, and the same outcome. This means that system.debug is not giving me the truth when it comes to logging the values of X and Y in the actual system. Or dark magic. :( Nov 22 '19 at 21:48
• So wait, Im not understanding, your question said it was wrong, but now you are getting the same result as me. So which is it? Nov 22 '19 at 21:50
• The calculations are correct whenever I make an entirely new object, just like you did. However in my original object (which has much more cruft, etc), the formula field is calculating wrong. While the formula field is simple subtraction (just like you have in `zfld__c`), it is calculating to be `0.01`, instead of `0.00`. This is despite the X and Y of that formula both being `-0.01` per `System.debug` each field... I wonder if System.debug truncates somehow by default? seems like a silly notion. Nov 22 '19 at 21:54
• Is there anyway you can show a workbench query of the exact records in question Nov 22 '19 at 21:57
• Sure. --- Values in order of Object ID, X, Y, and Z perspectively. a5x19000000KDJsAAO -0.01 -0.01 0.01 Nov 22 '19 at 22:01