What is the correct way to do calculations [duplicate]

2

I'm doing a function of product calculations. In the following scenarios:

  • User can add
  • User can give discount (discount on value + addition)
  • User can give partner discount (discount on original value)

Function example:

function calcularValor(valorOriginal, acrescimo, desconto, descontoParceiro)
{
   var valorAcrescimo = (valorOriginal / ((100 - acrescimo) / 100)) - valorOriginal ;
   var valorDesconto = ((valorOriginal + valorAcrescimo) / 100) * desconto;
   var valorDescontoParceiro = (valorOriginal / 100) * descontoParceiro;

   return valorOriginal + valorAcrescimo  - valorDesconto  - valorDescontoParceiro;     
}

But the problem is this: When I save the value it is not hitting 1 cent (it is not significant for 1 request, but for 1000 requests it is already making a nice difference), because I save valorAcrescimo , valorDesconto , valorDescontoParceiro to 2 decimal places.

How would you work around this problem?

Do the calculation and already round the value and use to do the other calculation? (According to valorAcrescimo )

    
asked by anonymous 13.11.2017 / 14:39

1 answer

2

Problem apparently solved.

I've used the answer function:

Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };

And in my function I left calculating with floating numbers, but when I saved I used 2 decimal places. If the third house after the comma is greater than or equal to 5, round up.

    
13.11.2017 / 16:55