Currency Convertor Using Math.js Javascript Library and Fixer.io

For this currency convertor to work we have to link the math.js Javascript library and pull the current currency conversion rates from fixer.io.

Using a text inbox you can generate almost and string of currency values. I have the decimal place set to 2 but you can change that to be more or less by changing the precision value in this line:


 var resultStr = math.format(math.eval(expr.value), {notation: 'fixed', precision: 2})
<!DOCTYPE html>
<html>
<head>
  <title>Currency Conversion</title>

  <script src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.11.5/math.min.js"></script>

  <style>
    body,
    html,
    input {
      font-size: 11pt;
      font-family: Gotham, Verdana, Arial, Sans-Serif;
      color: #4d4d4d;
      max-width: 600px;
    }

    h1 {
      font-size: 120%;
    }

    input {
      padding: 5px;
      width: 400px;
    }
    .lbl {
      font-size: 13px;
    }
  </style>
</head>
<body>

<p id="info">
  fetching currencies...
</p>
<p>
  <label class="lbl" for="expr">Enter an expression with currencies:</label><br>
  <label class="lbl" for="expr">EXAMPLE: 25 GBP + 5 EUR + 25 AUD in USD</label><br>
  <label class="lbl" for="expr">The above expression adds 25 British Pounds with 5 Euros and 25 Australian Dollars and outputs the amount in US Dollars.</label>
</p>
<div id="form" style="display: none;">
  <p>
    <input id="expr" value="25 GBP + 5 EUR + 25 AUD in USD" /><br/>
  </p>
  <p id="result"></p>
</div>

<script>
  fetchAndImportCurrencies()
      .then(function (currencies) {
        document.getElementById('expr').oninput = evaluate;
        document.getElementById('form').style.display = '';
        document.getElementById('info').innerHTML = 'Available currencies: ' + currencies.join(', ');

        evaluate();
      })

  function fetchAndImportCurrencies () {
    // this calls for the actuall currency conversion rates from fixer.io
    return fetch('https://api.fixer.io/latest')
        .then(function (response) {
          return response.json();
        }).then(function (data) {

          // import the currencies
          math.createUnit(data.base)
          Object.keys(data.rates).forEach(function (currency) {
            math.createUnit(currency, math.unit(1 / data.rates[currency], data.base));
          });

          // return an array with all available currencies
          return Object.keys(data.rates).concat(data.base);
        });
  }

  function evaluate () {
    var expr = document.getElementById('expr');
    var result = document.getElementById('result');

    try {
// precision: 2 gives 2 decimal places.  
      var resultStr = math.format(math.eval(expr.value), {notation: 'fixed', precision: 2})
      result.innerHTML = '<span style="color: dodgerblue;">' + resultStr + '</span>';
    }
    catch (err) {
      result.innerHTML = '<span style="color: red;">' + err.toString() + '</span>';
    }
  }
</script>
</body>
</html>