Calculating interest with javascript

Asked

Viewed 2,715 times

4

I’m having trouble putting together a script, I’m not knowing how to calculate date interaction with javascript, I was thinking of making a screen that calculates interest, but returns the values in real time in the inputs that are disabled

follows code:

<fieldset>
   <legend>Calcular Juros</legend>

   <label>Data de Vencimento:</label>
   <input id="datavenc" type="date"/><br />

   <label>Data de Pagamento: </label>
   <input id="datapag" type="date"/><br />

   <label>Valor do Titulo: </label>
   <input id="valortitulo" type="text"/><br />

   <label>Outras Despesas: </label>
   <input id="despesas" type="text"/><br /><br />

   <label>Dias em Atraso: </label>
   <input id="diasematraso" type="text" disabled/><br />

   <label>Juros: </label>
   <input id="juros" type="text" disabled/><br />

   <label>Valor Total a Pagar: </label>
   <input id="valortotal" type="text" disabled/><br />
</fieldset>

For example,
Due date = 01/09/2017
payment date = 30/09/2017
value of the title = 2000
other expenditure = 100

days late = 29
interest = 96,67
total value payable= 2.196,67

Days late = due date - payment date
Interest = (value of security * 5%)/30*days late
Other expenditure = expenditure
Amount payable = Security value + interest + expenses

2 answers

1

The calculations you indicate are relatively simple, just keep the values in variables or constants and using in the following operations, since they are chained.

In my example I used Array Destructuring to simplify the search of the elements on the form through its ids and Arrow Functions to the click, which you can exchange if you are working with old browsers.

const [dataVenc, dataPag, valorTitulo, despesas, diasEmAtraso, juros, valorTotal, calcular] = 
document.querySelectorAll("#datavenc, #datapag, #valortitulo, #despesas, #diasematraso, #juros, #valortotal, #calcular");

calcular.addEventListener("click", () => {  

  const diasAtraso = (new Date(dataPag.value).getTime() - new Date(dataVenc.value).getTime()) / (1000 * 3600 * 24);
  
  const vTit = Number(valorTitulo.value);
  let jurosCalculados = 0;
  
  if (diasAtraso > 0){ //apenas calcula juros quando há dias em atraso
    diasEmAtraso.value = diasAtraso;
    jurosCalculados = (vTit * 0.05) / 30 * diasAtraso;
  }
  else { //se não tem dias em atraso os juros continuam a 0
    diasEmAtraso.value = 0;
  }
  
  juros.value = jurosCalculados.toFixed(2);
  valorTotal.value = (vTit + jurosCalculados + Number(despesas.value)).toFixed(2);
});
<form>
  <fieldset>
     <legend>Calcular Juros</legend>

     <label>Data de Vencimento:</label>
     <input id="datavenc" type="date"/><br />

     <label>Data de Pagamento: </label>
     <input id="datavenc" type="date"/><br />

     <label>Valor do Titulo: </label>
     <input id="valortitulo" type="text"/><br />

     <label>Outras Despesas: </label>
     <input id="despesas" type="text"/><br /><br />

     <label>Dias em Atraso: </label>
     <input id="diasematraso" type="text" disabled/><br />

     <label>Juros: </label>
     <input id="juros" type="text" disabled/><br />

     <label>Valor Total a Pagar: </label>
     <input id="valortotal" type="text" disabled/><br />
  </fieldset>
</form>
<button id="calcular">Calcular</button>

Although I did not indicate, I assumed that interest would only be calculated if the payment date was higher than the due date.

  • I think there must be something wrong with these accounts... hehe

  • In querySelectorAll you are repeating datavenc twice;

  • @acklay Oops, thanks lol, hadn’t even noticed.

  • @acklay It was also missing to calculate, but also already put. The rest seems to me correct.

  • The date is reversed as well. By the logic of the question, that would be exactly a late interest calculation. Generally the payment date would be after maturity.

  • @acklay This I did purposefully, for the example of the AP. If it is as you say it becomes negative. But I can always convert to positive, that maybe it’s better

  • Are you sure that your logic is as it should be?! I’m picking on you because I was making an answer and you were faster. After I erased that I saw that there was a lot of error in yours. ehuehuhe but let’s work on it there to help the guy;

  • @acklay But you can put yours without problem. I logic I have limited myself to following the accounts that the AP wants to do. And in this sense it seems to coincide with the calculations in the question. Even the values coincide with the result he expected.

  • I already blacked out! heuheuheuh laziness. But test for you see, something is still going wrong.

Show 4 more comments

1


Solution that automatically updates values when any field is modified as it is completed in real time:

elementsArray = document.getElementsByTagName('input');
for(x=0;x<elementsArray.length;x++){
	elementsArray[x].addEventListener("input", function(){
		calcula();
	});
}

function calcula(){
	vencimento = document.getElementById("datavenc").value;
	pagamento = document.getElementById("datapag").value;

	if(document.getElementById("datavenc").type !== "date"){
		// para o Firefox que não suporta type="date"
		venc_array = vencimento.split("/");
		pagt_array = pagamento.split("/");
		vencimento = venc_array[2] + "-" + venc_array[1] + "-" + venc_array[0];
		pagamento = pagt_array[2] + "-" + pagt_array[1] + "-" + pagt_array[0];
	}

	d1 = new Date(vencimento);
	d2 = new Date(pagamento);

	dias_atraso = parseInt((d2 - d1) / (24 * 3600 * 1000));

	valortit = parseFloat(document.getElementById("valortitulo").value);
	outrasdesp = document.getElementById("despesas").value;
	outrasdesp = (outrasdesp == "") ? 0 : parseFloat(outrasdesp);

	juros = ((valortit * .05) / 30) * (dias_atraso);

	if (!isNaN(dias_atraso) && !isNaN(juros)) {
		document.getElementById("diasematraso").value = dias_atraso;
		document.getElementById("juros").value = juros.toFixed(2).replace(".", ",");
		document.getElementById("valortotal").value = (valortit + juros + outrasdesp).toFixed(2).replace(".", ",");
	}
}
<fieldset>
   <legend>Calcular Juros</legend>

   <label>Data de Vencimento:</label>
   <input id="datavenc" type="date"/><br />

   <label>Data de Pagamento: </label>
   <input id="datapag" type="date"/><br />

   <label>Valor do Titulo: </label>
   <input id="valortitulo" type="text"/><br />

   <label>Outras Despesas: </label>
   <input id="despesas" type="text"/><br /><br />

   <label>Dias em Atraso: </label>
   <input id="diasematraso" type="text" disabled/><br />

   <label>Juros: </label>
   <input id="juros" type="text" disabled/><br />

   <label>Valor Total a Pagar: </label>
   <input id="valortotal" type="text" disabled/><br />
</fieldset>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.