How to Create a Currency Converter in JavaScript?

In this tutorial, we will be discussing how to create a currency converter in JavaScript. We will be discussing the various steps involved in creating such a converter.

What is a Currency Converter?

A currency converter is a tool that helps you convert one currency to another. For example, if you are from the United States and you are traveling to Europe, you will need to use a currency converter to convert your US dollars into Euros.

Why Use JavaScript to Create a Currency Converter?

JavaScript is a versatile programming language that can be used to create a wide variety of applications, including web-based applications. When it comes to creating a currency converter, JavaScript provides a number of advantages, such as:

  • Ease of use ? JavaScript is relatively easy to learn and use, compared to other programming languages. This makes it an ideal choice for creating a currency converter application.
  • Cross-platform compatibility ? JavaScript code can be executed on different platforms, such as Windows, Mac, and Linux. This makes it possible to create a currency converter that can be used by people on different platforms.
  • Real-time updates ? JavaScript can fetch live exchange rates from APIs, ensuring accurate conversions.

Building a Currency Converter

Let's create a complete currency converter that fetches real-time exchange rates. The converter will include a user-friendly interface and handle the conversion logic.

<!doctype html>
<html>
<head>
   <title>Currency Converter in JavaScript</title>
   <style>
      body { 
         font-family: Arial, sans-serif; 
         max-width: 500px; 
         margin: 50px auto; 
         padding: 20px; 
      }
      .converter { 
         background: #f5f5f5; 
         padding: 20px; 
         border-radius: 8px; 
      }
      input, select, button { 
         padding: 8px; 
         margin: 5px; 
         border: 1px solid #ddd; 
         border-radius: 4px; 
      }
      button { 
         background: #007bff; 
         color: white; 
         cursor: pointer; 
      }
      #result { 
         margin-top: 15px; 
         font-weight: bold; 
         color: #28a745; 
      }
   </style>
</head>
<body>
   <div class="converter">
      <h1>Currency Converter</h1>
      <p>Select currencies and enter amount to convert.</p>
      
      <label>From:</label>
      <select id="from">
         <option value="USD">USD - US Dollar</option>
         <option value="EUR">EUR - Euro</option>
         <option value="GBP">GBP - British Pound</option>
         <option value="INR">INR - Indian Rupee</option>
         <option value="JPY">JPY - Japanese Yen</option>
      </select>
      
      <label>To:</label>
      <select id="to">
         <option value="USD">USD - US Dollar</option>
         <option value="EUR">EUR - Euro</option>
         <option value="GBP">GBP - British Pound</option>
         <option value="INR">INR - Indian Rupee</option>
         <option value="JPY">JPY - Japanese Yen</option>
      </select>
      
      <br><br>
      <label>Amount:</label>
      <input type="number" id="amount" placeholder="Enter amount" min="0" step="0.01" />
      <button type="button" id="convert">Convert</button>
      
      <div id="result"></div>
      <div id="loading" style="display:none; color:#666;">Converting...</div>
   </div>

   <script>
      const convertBtn = document.getElementById("convert");
      const result = document.getElementById("result");
      const loading = document.getElementById("loading");
      const fromSelect = document.getElementById("from");
      const toSelect = document.getElementById("to");
      const amountInput = document.getElementById("amount");

      convertBtn.addEventListener("click", function() {
         const fromCurrency = fromSelect.value;
         const toCurrency = toSelect.value;
         const amount = parseFloat(amountInput.value);

         // Validate input
         if (!amount || amount <= 0) {
            result.innerHTML = "Please enter a valid amount";
            result.style.color = "#dc3545";
            return;
         }

         if (fromCurrency === toCurrency) {
            result.innerHTML = `${amount} ${fromCurrency} = ${amount} ${toCurrency}`;
            result.style.color = "#28a745";
            return;
         }

         // Show loading
         loading.style.display = "block";
         result.innerHTML = "";

         // Fetch exchange rates
         fetch(`https://api.exchangerate-api.com/v4/latest/${fromCurrency}`)
            .then(response => {
               if (!response.ok) {
                  throw new Error('Failed to fetch exchange rates');
               }
               return response.json();
            })
            .then(data => {
               const rate = data.rates[toCurrency];
               const convertedAmount = (rate * amount).toFixed(2);
               
               result.innerHTML = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
               result.style.color = "#28a745";
               loading.style.display = "none";
            })
            .catch(error => {
               result.innerHTML = "Error: Unable to fetch exchange rates. Please try again.";
               result.style.color = "#dc3545";
               loading.style.display = "none";
               console.error('Conversion error:', error);
            });
      });

      // Allow Enter key to trigger conversion
      amountInput.addEventListener("keypress", function(event) {
         if (event.key === "Enter") {
            convertBtn.click();
         }
      });
   </script>
</body>
</html>

How It Works

The currency converter works in several steps:

  1. User Input ? Users select source and target currencies, then enter an amount
  2. API Request ? The application fetches current exchange rates from a free API
  3. Calculation ? JavaScript multiplies the amount by the exchange rate
  4. Display Result ? The converted amount is displayed with proper formatting

Key Features

  • Real-time rates ? Uses live exchange rate API for accurate conversions
  • Input validation ? Checks for valid amounts and handles errors gracefully
  • User-friendly interface ? Clean design with loading indicators and keyboard support
  • Error handling ? Displays helpful messages when API calls fail

Extending the Converter

You can enhance this converter by:

  • Adding more currencies to the dropdown lists
  • Implementing historical exchange rate charts
  • Adding currency symbols and flags
  • Storing conversion history in localStorage

Conclusion

Creating a currency converter in JavaScript is straightforward using modern APIs and DOM manipulation. This example demonstrates fetching real-time exchange rates, handling user input validation, and providing a responsive user interface for accurate currency conversions.

Updated on: 2026-03-15T23:19:00+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements