3
I’m working with values (decimal(18,2)
) a sale where the sum of the price of the products is to be converted into a number of parcels. So that I can divide the total of the products exactly for the plots, I also need to calculate the leftover division and then apply this leftover to a single final plot. For that I do:
var parcelas = 3;
var produtos = [
{nome: 'bola', valor: 10},
{nome: 'pipa', valor: 5.3},
{nome: 'carro', valor: 15}
];
//total dos produtos (resultado = 30.3 ~> R$30,30)
var total = 0;
for(var i in produtos){
total = total + produtos[i].valor;
}
//verifico se há resto na divisão
var restoDivisao = total % parcelas
When I check if there’s the rest in the division, it’s returning 0.30
but if I share 30.3 / 3
the result is 10.1
.
What is the correct way for me to check if there is rest in a division with decimal values?
Doing tests, somehow I managed to do so:
var restoDivisao = (((total) * 100) % parcelas) / 100;
This way works but I can’t accept that there really isn’t a more "clean" method than this. There is a more visually correct way to get to the rest of this division?
yes that way it works but if when I have a reference where the value of the sum of the plots is higher, when I use its calculation it does not arrive at the solution,
var parcelas = 6, valor =10; var resto = (((valor) * 100) % parcelas) / 100; var cada = parseFloat((total / parcela).toFixed(2)); var ultima = parseFloat((cada + resto).toFixed(2)); //resultado ~> ((6 * cada) + ultima).toFixed(2) = 10.06
– LeandroLuk
@Leandroluk edited the variable calculation
cadaParcela
to avoid this problem.– Marco Aurélio Deleu