I’m creating a currency converter, and it returns a wrong value

Asked

Viewed 54 times

-2

From mult3 it returns a wrong value, in mult3 for example it has to return 0.83 when the sent value is 1, but returns 0.15 which is wrong.

  let money_cov = {
      get_in(){
          let select = document.getElementById('moeda_in');
          let value = select.options[select.selectedIndex].value;
          return value;
      },
      get_out(){
          let select = document.getElementById('moeda_out');
          let value = select.options[select.selectedIndex].value;
          return value;
      },
      mul(){
          switch (this.get_in(),this.get_out()) {
           case 'real', 'dolar':
              let mult_real_dolar = (parseFloat(document.getElementById("valor_entrada").value)) * 0.18;
              alert(mult_real_dolar.toLocaleString('pt-br', { style: 'currency', currency: 'BRL'}));
           break;
           case 'real', 'euro':
              let mult_real_euro = (parseFloat(document.getElementById("valor_entrada").value)) * 0.15;
              alert(mult_real_euro.toLocaleString('pt-br', { style: 'currency', currency: 'BRL'}));    
           break;
           case 'dolar', 'real':
              let mult_dolar_real = (parseFloat(document.getElementById("valor_entrada").value)) * 5.59;
              alert(mult_dolar_real.toLocaleString('pt-br', { style: 'currency', currency: 'USD'}));    
           break;
           case 'dolar', 'euro':
              let mult_dolar_euro = (parseFloat(document.getElementById('valor_entrada').value)) * 0.83;
              alert(mult_dolar_euro.toLocaleString('pt-br', { style: 'currency', currency: 'USD'}));
           break;
           case 'euro', 'real':
              let mult_euro_real = (parseFloat(document.getElementById('valor_entrada').value)) * 6.73;  
              alert(mult_euro_real.toLocaleString('pt-br', { style: 'currency', currency: 'EUR'}));   
           break;
           case 'euro', 'dolar':     
              let mult_euro_dolar = (parseFloat(document.getElementById('valor_entrada').value)) * 1.20;   
              alert(mult_euro_dolar.toLocaleString('pt-br', { style: 'currency', currency: 'EUR'})); 
           break;
           default:
               alert('Erro!');
          }
      },
  }
<div>
  <label for="moeda_in">Moeda de entrada:</label>
  <select name="valor_in" id="moeda_in">
    <option value="real" selected>Real Brasileiro</option>
    <option value="dolar">Dolar Americano</option>
    <option value="euro">Euro</option>
  </select>
  <br>
  <label for="moeda_out">Moeda de saida:</label>
  <select name="valor_out" id="moeda_out">
    <option value="real">Real Brasileiro</option>
    <option value="dolar" selected>Dolar Americano</option>
    <option value="euro">Euro</option>
  </select>
</div>
<!-- Entrada de Valores a Serem Convertidos || Botao para mostrar Resultado -->
<div>
  <input type="number"  id="valor_entrada" value="1">
  <button type="submit" onclick="money_cov.mul()">Send</button>
</div>

  • What do you mean, "I can’t"? Some mistake?

  • from mult3 it returns a wrong value, in mult3 for example it has to return 0.83 when the sent value is 1, but returns 0.15 which is wrong. Got it?

2 answers

1

Heed:

Monetary values should not be modelled as floating point numbers due to intrinsic imprecision of the numerals described in the standard IEEE 754.

The scope of this response is restricted to the codification of the logical solution of the exercise.

For more details see:

How to represent money in Javascript?

It’s a very verbose code for a simple problem.

In its literal object money_cov the functions get_in() and get_out() are performing unnecessary processing, since the element HTML <select> has the attribute value which reflects the value of the element HTML selected. Easily these functions can be exchanged for a property associated with a getter.

As to function mul() a complex verification structure is created where a simple division solves the problem:

Creating a table where the real is fixed as a unit and the other currency as multiples of that real.

Coin Coefficient(R$)
real 1.00
dollar 5.59
euro 6.73

Conversion table.

The result of the conversion is equal to the quantity to be converted times the coefficient of the input currency divided by the coefficient of the exit currency:

    Valorconvertido = (Valorentrada * Coeficienteentrada) / Coeficientesaída
 

To facilitate the formatting of the output a table of monetary locations has also been created:

Coin ISO 4217 code
real BRL
dollar USD
euro EUR

Partial table ISO 4217.

const tabela_coef = {
  real: 1.00,
  dolar: 5.59,
  euro: 6.73
}

const tabela_loc = {
  real: "BRL",
  dolar: "USD",
  euro: "EUR"
}

const money_cov = {
  get in() {
    return document.getElementById('moeda_in').value;
  },
  get out() {
    return document.getElementById('moeda_out').value;
  },
  mul() {
    let entrada = parseFloat(document.getElementById('valor_entrada').value);
    let converção = entrada * tabela_coef[this.in] / tabela_coef[this.out];
    alert(converção.toLocaleString('pt-br', {
      style: 'currency',
      currency: tabela_loc[this.out]
    }));
  }
};
<div>
  <label for="moeda_in">Moeda de entrada:</label>
  <select name="valor_in" id="moeda_in">
    <option value="real" selected>Real Brasileiro</option>
    <option value="dolar">Dolar Americano</option>
    <option value="euro">Euro</option>
  </select>
  <br>
  <label for="moeda_out">Moeda de saida:</label>
  <select name="valor_out" id="moeda_out">
    <option value="real">Real Brasileiro</option>
    <option value="dolar" selected>Dolar Americano</option>
    <option value="euro">Euro</option>
  </select>
</div>
<!-- Entrada de Valores a Serem Convertidos || Botao para mostrar Resultado -->
<div>
  <input type="number" id="valor_entrada" value="1">
  <button type="button" onclick="money_cov.mul()">Send</button>
</div>

0

The switch in Javascript does not allow multiple parameters of the way you encoded, separating the values in the case comma. Change the logic to if/else to be able to compare the value of 2 variables or use a value key type object as I did below in the refactoring of your code.

let money_cov = {
  get_in() {
    let select = document.getElementById('moeda_in');
    let value = select.options[select.selectedIndex].value;
    return value;
  },
  get_out() {
    let select = document.getElementById('moeda_out');
    let value = select.options[select.selectedIndex].value;
    return value;
  },
  mul() {
    const possibilidades = {
      'real->dolar': {
        fator: 0.18,
        currency: 'BRL'
      },
      'real->euro': {
        fator: 0.15,
        currency: 'BRL'
      },
      'dolar->real': {
        fator: 5.59,
        currency: 'USD'
      },
      'dolar->euro': {
        fator: 0.83,
        currency: 'USD'
      },
      'euro->real': {
        fator: 6.73,
        currency: 'EUR'
      },
      'euro->dolar': {
        fator: 1.20,
        currency: 'EUR'
      },
    };

    const opcaoSelecionada = `${this.get_in()}->${this.get_out()}`;
    console.log(opcaoSelecionada);
    const parametros = possibilidades[opcaoSelecionada];

    if (!parametros) {
      alert('Não implementado');
      return;
    }

    const valorEntrada = (parseFloat(document.getElementById("valor_entrada").value));
    const valorSaida = valorEntrada * parametros.fator;
    console.log(valorSaida);

    alert(valorSaida.toLocaleString('pt-br', {
      style: 'currency',
      currency: parametros.currency
    }));
  },
}
<div>
    <label for="moeda_in">Moeda de entrada:</label>
    <select name="valor_in" id="moeda_in">
         <option value="real" selected>Real Brasileiro</option>
         <option value="dolar">Dolar Americano</option>
         <option value="euro">Euro</option>
    </select>        

    <br>

    <label for="moeda_out">Moeda de saida:</label>
    <select name="valor_out" id="moeda_out">
         <option value="real">Real Brasileiro</option>
         <option value="dolar" selected>Dolar Americano</option>
         <option value="euro">Euro</option>
    </select>   
</div>

<!-- Entrada de Valores a Serem Convertidos || Botao para mostrar Resultado -->

<div>
    <input type="number"  id="valor_entrada" value="1">
    <button type="submit" onclick="money_cov.mul()">Send</button>
</div>

Browser other questions tagged

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