# Trigger on account that equally divides the amount on related child contacts in such a way that the total should be equal

My question is , I need to divide the amount in such a way that the addition of all should be equal to total amount.

With the below trigger my answer is coming as :- If the amount on contact is 50 & three related contacts are there , then its divided as 50/3 = 16.67 each but total is 50.01 which is incorrect.

I need it as 50 , It can be divided in anyway like two contacts same and another contact different

trigger AccountTrigger on Account (after update) {

``````List<Contact> conListToUpdate = new List<Contact>();
for(Account acc : [SELECT Id,Total__c, (SELECT Id, Share__c FROM Contacts) FROM Account WHERE Id IN : Trigger.new]){

if(acc.Total__c != null){
Integer contactNumber = acc.Contacts.size();
Decimal shareEachContact = 0;
if(contactNumber  > 0){
shareEachContact = acc.Total__c / contactNumber;
}

for(Contact con : acc.Contacts){
con.Share__c = shareEachContact;

}
}
}

update conListToUpdate;
``````

}

The discrepancy that you see is likely due to rounding by Salesforce. The best way to achieve this would be to put sane share to all contacts (n) except the last one (nth). There you can subtract the total of (n-1) contact from account total.

``````trigger AccountTrigger on Account (after update) {

List<Contact> conListToUpdate = new List<Contact>();
for (Account acc : [SELECT Id,Total__c, (SELECT Id, Share__c FROM Contacts) FROM Account WHERE Id IN :Trigger.new]) {

if (acc.Total__c != null) {
Integer contactNumber = acc.Contacts.size();
Decimal shareEachContact = 0;
if (contactNumber > 0) {
shareEachContact = Math.floor(acc.Total__c / contactNumber);
}

for (Integer i = 0; i < acc.Contacts.size(); i++) {
if (i == (contactNumber - 1)) {
acc.Contacts[i].Share__c = acc.Total__c - (shareEachContact * (contactNumber - 1));
} else {
acc.Contacts[i].Share__c = shareEachContact;
}
}
}
}

update conListToUpdate;

}
``````

If you need to divide a number that doesn't divide evenly, you'll need to use the math.mod operator. Then remove the excess. For example:

``````Integer totalToDivide = 50;
Integer numberOfContacts = 3;
Integer remainder = Math.mod(totalToDivide, numberOfContacts); //equals 2
Integer evenlyDivisible = totalToDivide - remainder;  //equals 48
Integer amountToAllocateToContacts = evenlyDivisible / numberOfContacts;
//then give one contact the remainder or discard if not needed
contact += remainder
``````