# How to divide Oppo RSF field on Oppo Products into equal amounts based on # of Oppo Products

In opportunity line item/product we have custom field called break up fee ...which will filled if the opportunity is closed lost.

In oppy we have a roll up field will calculate the sum of all break up amounts of products.

Need a back fill, need to divide the total break up amount into equal parts but decimal variation is coming like Total break up amount is 175000.0 ,but wonder when dividing by 3 it is giving value as 58333.333333333336 and that value *3 is giving s 175000.0000000008 which is inaccurate...

please let me know if you have come across this situation. thanks in advance.

• Uday - might be worth explaining in more detail by what you mean by 'back fill'. But, if your problem is that (x / n) rounded * n != x - you're just going to have to allocate the overage/underage to one of the items. This is the nature of rounded decimal arithmetic – cropredy May 7 '14 at 16:22
• back filling is it is newly added field ..so we need to add data to existing oppys's in system. – user7601 May 8 '14 at 7:06
• Did you manage to get your issue resolved? – Alex Tennant Jul 9 '14 at 8:59

## 2 Answers

When doing math like that you should always get the final result in the scale that you require

So after you multiply and divide and do all the things you want set the scale back to the original....

Decimal finalVal = YOURCALCULATIONS; finalValue = finalValue.setScale(ORIGINALVALUE.scale());

Here is some dev console code to illustrate

``````Decimal s = 17500.0;
Decimal d = s/3;
system.debug(logginglevel.error,d);
Decimal m = d*3;
system.debug(logginglevel.error,m);
m = m.setScale(s.scale());
system.debug(logginglevel.error,m);
``````

You are suffering from a combination of issues here, first is the choice by SFDC to use a floating-point representation for currency fields (this is covered in the `Decimal` documentation).

A number that includes a decimal point. Decimal is an arbitrary precision number. Currency fields are automatically assigned the type Decimal.

The second issue is the floating point precision (or rather, the lack of). In short, 1/3 cannot be exactly represented by an IEEE-754 floating-point number.

At some point when dealing with currency in floating-point format you need to make the decision to round (preferably after all of your calculations, using `setScale` in SFDC) and then deal with the result of that rounding. For example, if you use `setScale` on your final result to set the precision to decimal places you will get the correct result.

``````Decimal d = 175000.0000000008;
System.debug(d.setScale(2));
``````

Here is a Stack Overflow answer which gives you the short version of why floats and double are not suitable for use in currency calculations, Oracle also host a fantastic journal article by David Goldberg on their site which goes into great detail about the issues with floating point numbers: