jeudi 7 juin 2018

Can I force percentages to sum up to a exact value?

I have a fixed tax value, say USD 50,00, and I want to divide this tax among people. So, one person can select how much of the tax he will pay. Once this person selects its quota, the remaining of the tax is divided among the others.

I have made a javascript(I am using EmberJs) function to do this automatically but sometimes the value is evaluated to more than USD 50 and sometimes less.

My function:

 percentageFromValue(person, selectedValue){
        selectedValue = selectedValue.replace(/[R$\s]/g,'');
        selectedValue = selectedValue.replace(/[,]/g,'.');
        selectedValue = parseFloat(selectedValue);
        let taxValue= this.get('taxValue'); 
        ///nao deixar valor utrapasse o valor da taxa
        if(selectedValue> taxValue)
            valor = taxValue;

        let personPercentage = (selectedValue*100.0 / taxValue);
        personPercentage = parseFloat(personPercentage );
        let parcialSum= 0;


        person.set('pctTax',personPercentage.toFixed(2));

        let remainingPercent= 100.0 - personPercentage ;
        let totalPersons = this.get('persons.length');
        let pctPerPerson= remainingPercent/ (totalPersons - 1);
        let valuePerPerson= (pctPerPerson* taxValue) / 100.0;

        this.get('persons').forEach(r =>{
            if(person.get('id') != r.get('id')){
                r.set('pctTax',pctPerPerson);
                r.set('value',valuePerPerson.toFixed(2));
            }
        });

    },

How Can I make this automatic redistributions to always sum up to USD 50,00??




Aucun commentaire:

Enregistrer un commentaire