0

I have a rollup field on the Quote object. When I access that value in my VF page controller, I'm seeing its value getting truncated there. Because of this when I'm seeing less amount on my VF page.

The rollup field value is getting calculated from the formula field of currency type of the quote line item.

When I query this field in developer console, I see full value

Eg: Value in UI and developer Console : 2950

Value in Controller: 2949.999999999999999999999999999999999998

Query I'm using Quote quoteRecord = [SELECT Id, Total__c FROM Quote WHERE Id =: quoteId];

Integer totalAfterDiscount = (Integer)quoteRecord.Total__c

totalAfterDiscount = 2949

I know, I can use rounding methods like round(System.RoundingMode.CEILING)) to get the value back to 2950.

But I want to understand what is causing this value to truncate, I mean change value to 2949.999999999999999999999999999999999998

One thing which I noticed is that when my currency is USD (which is default org currency) I'm not getting this issue. but when my currency is GBP that time I'm getting this issue.

1

The UI shows 2950, because it rounds to the nearest 0.01 (currency fields have two decimals by default). If you had a value of 2949.98999999999999999, it'd show 2949.99 instead.

When you cast from a Decimal to an Integer, the entire value after the Decimal point is dropped. As far as I'm aware, this is true in every language that supports floating point numbers and integer numbers.

"Down casting" to a narrower type discards the fractional value without rounding, which is the reason why programmers can't assign a Decimal to an Integer value without casting. This is the programmer acknowledging to the compiler that there may be a loss of data, and they are willing to accept this loss.

If you want to get to the nearest integer, you need to use Math.round or other such tricks (such as: Integer totalAfterDiscount = (Integer)(quoteRecord.Total__c+0.5);).

Note that this truncation is always towards zero, since we are discarding the fractional data:

Integer i = (Integer)-1.999999999; // -1
2
  • My formula value is UnitPrice * Quantity which is 2950 * 1 = 2950, and with rollup field it should be 2950. But only in controller it's 2949.989999 – salesforce Developer Feb 17 at 17:40
  • @salesforceDeveloper You need to check your conversion rates, unit price, and quantity to make sure there are no hidden fractional values. – sfdcfox Feb 17 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.