Calculate change and display notes available with JavaScript

I have a class activity to do, where I must receive from the user the amount of the purchase and the amount paid, and then display the change. Until then ok, only it also asks to display in a textarea the notes used in the exchange, always informing the minimum possible notes, example:

vlrCompra = 53,00
vlrPago = 100,00
vlrTroco = 47,00 

notasTroco = 
4 notas de 10,00
1 nota   de  5,00
2 notas  de  1,00

I have no idea how to do that last part, someone to help me? THE NOTES I HAVE AVAILABLE ARE 1, 5, 10, 50

Here's what I did until now:

function calculaTroco(){

    var valorCompra = parseFloat($("#valorCompra").val());
    var valorPago = parseFloat($("#valorPago").val());
    var valorTroco = 0;


    if (valorPago == valorCompra){
        valorTroco = 0;
        $("#valorTroco").val(valorTroco);
        alert("Não gerou troco");

    }else if(valorPago > valorCompra){

        valorTroco = valorPago - valorCompra;
        $("#valorTroco").val(valorTroco);

    }else{
        alert("Não gerou troco (Valor pago menor que valor da compra)");
    }

    $("#valorCompra").val("");
    $("#valorPago").val("");
    $("#valorCompra").focus();
}

Remembering that I need to make this part of the notes in another function, so far we have learned array, for...

Part of HTML:

<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="utf-8"/>
        <title>Calcular Troco</title>
        <script type="text/javascript" src="jquery.js"></script>
    </head>
    <body>

        <form id="formulario">
            <fieldset>
                <legend>Calcular Troco</legend>

                <label for="valorCompra" >Valor da compra:</label>
                <input type="text" id="valorCompra" name="valorCompra" /><br />

                <label for="valorPago" >Valor pago:</label>
                <input type="text" id="valorPago" name="valorPago" /><br /><br />

                <button type="button" id="button" onclick="calculaTroco()">Calcular troco</button><br /><br />

                <label for="valorTroco" >Valor do troco:</label>
                <input type="text" id="valorTroco" name="valorTroco" readonly="readonly"/><br /><br />  

                <label for="notasUtilizadas">Notas utilizadas:</label>
                <textarea rows="3" id="notasUtilizadas" readonly="readonly" ></textarea><br/>

            </fieldset>
        </form>
    <script type="text/javascript" src="troco.js"></script>
    </body>

</html>
Author: Sam, 2019-07-22

3 answers

Create your own function to calculate the notes and use an array with the values in descending order:

var notas = [50,10,5,1];

Send the value of the change to the function and loop the array by deducting the value of the change by dividing the number of notes x the value of the array note, creating a string with the information that will be sent to the textarea. In the end the function will return the string with the right amount of notes.

See:

function calculaTroco(){

    var valorCompra = parseFloat($("#valorCompra").val());
    var valorPago = parseFloat($("#valorPago").val());
    var valorTroco = 0;
    
    if (valorPago == valorCompra){
        valorTroco = 0;
        $("#valorTroco").val(valorTroco);
        alert("Não gerou troco");

    }else if(valorPago > valorCompra){

        valorTroco = valorPago - valorCompra;
        $("#valorTroco").val(valorTroco);
        
        // envia para o textarea o retorno da função calculaNotas
        $("#notasUtilizadas").val(calculaNotas(valorTroco));

    }else{
        alert("Não gerou troco (Valor pago menor que valor da compra)");
    }

    $("#valorCompra").val("");
    $("#valorPago").val("");
    $("#valorCompra").focus();

}

// função para calcular as notas
function calculaNotas(troco){
   var notas = [50,10,5,1];
   var texto = '';
   for(var x=0; x < notas.length; x++){
      if(troco >= notas[x]){
         var div = Math.floor(troco/notas[x]);
         texto += div + " notas de "+notas[x]+"\n";
         troco -= div*notas[x];
      }
      
   }
   return texto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formulario">
   <fieldset>
       <legend>Calcular Troco</legend>

       <label for="valorCompra" >Valor da compra:</label>
       <input type="text" id="valorCompra" name="valorCompra" /><br />

       <label for="valorPago" >Valor pago:</label>
       <input type="text" id="valorPago" name="valorPago" /><br /><br />

       <button type="button" id="button" onclick="calculaTroco()">Calcular troco</button><br /><br />

       <label for="valorTroco" >Valor do troco:</label>
       <input type="text" id="valorTroco" name="valorTroco" readonly/><br /><br />  

       <label for="notasUtilizadas">Notas utilizadas:</label>
       <textarea rows="3" id="notasUtilizadas" readonly ></textarea><br/>

   </fieldset>
</form>
 4
Author: Sam, 2019-07-22 20:06:56

This is an example of how to iterate over an array of notes, and use Association to store the amount of each. I leave the manipulation of this result with you.

function gerarTroco(valor) {
  // Notas disponíveis
  var notas = [50, 10, 5, 1]
  // Troco é um objeto, associando notas com a quantidade necessária
  var troco = {'50': 0, '10': 0, '5': 0, '1': 0}
  
  // Itero sobre o array de notas
  for (var nota of notas) {
    // Se o valor restante for maior que minha nota atual..
    while (valor >= nota) {
      // incremento a propriedade do objeto correspondente a nota
      troco[nota] += 1
      // e reduzo o valor restante pelo valor da nota
      valor -= nota
    }
  }

  return troco
}

console.log('Troco para 58:', gerarTroco(58))
 7
Author: user156436, 2019-07-22 19:45:04

I did it once using node, which worked great!

function sacarDinheiro(valorSaque) {
    let contador100 = 0
    let contador50 = 0
    let contador10 = 0
    let contador5 = 0
    let contador1 = 0
    let valorNota = calcularValorNota(valorSaque)
    while (valorSaque >= valorNota) {
        switch (valorNota) {
            case 100:
                valorSaque -= 100
                contador100++
                break
            case 50:
                valorSaque -= 50
                contador50++
                break
            case 10:
                valorSaque -= 10
                contador10++
                break
            case 5:
                valorSaque -= 5
                contador5++
                break
            case 1:
                contador1++
                valorSaque -= 1
                break
        }

        valorNota = calcularValorNota(valorSaque)

    }
    return elaborarResultado(contador100, contador50, contador10, contador5, contador1)
}

function calcularValorNota(valorSaque) {
    if (valorSaque >= 100) {
        return 100
    } else if (valorSaque >= 50) {
        return 50
    } else if (valorSaque >= 10) {
        return 10
    } else if (valorSaque >= 5) {
        return 5
    } else if (valorSaque >= 1) {
        return 1
    }
}

function elaborarResultado(contador100, contador50, contador10, contador5, contador1) {
    let resultado = ''

    if (contador100 > 0) {
        resultado += `${contador100} nota(s) de R$ 100. `
    }

    if (contador50 > 0) {
        resultado += `${contador50} nota(s) de R$ 50. `
    }

    if (contador10 > 0) {
        resultado += `${contador10} nota(s) de R$ 10. `
    }

    if (contador5 > 0) {
        resultado += `${contador5} nota(s) de R$ 5. `
    }

    if (contador1 > 0) {
        resultado += `${contador1} nota(s) de R$ 1. `
    }

    return resultado
}

console.log(sacarDinheiro(47))
console.log(sacarDinheiro(298));
 0
Author: Luciano Medeiros Delgado Motta, 2020-08-20 01:35:07