A Length Unit Converter for Meters and Feet

Using the magic command in jupyter notebook, I am able to write in HTML and javascript and interact with my conversions calculator.

%%html
<style>
  input {
    margin-bottom: 20px;
  }
</style>
<h2>Length Unit Converter</h2>
<label for="metersInput">Meters:</label>
<input type="number" id="metersInput" step="0.01" /><br />
<label for="feetInput">Feet:</label>
<input type="number" id="feetInput" step="0.01" /><br />
<button onclick="convertMetersToFeet()">Convert Meters to Feet</button>
<button onclick="convertFeetToMeters()">Convert Feet to Meters</button>
<script>
  // Conversion constants
  const METERS_TO_FEET = 3.28084;
  const FEET_TO_METERS = 0.3048;

  // defining the functions above
  function convertMetersToFeet() {
    const metersInput = document.getElementById("metersInput");
    const feetInput = document.getElementById("feetInput");

    const meters = parseFloat(metersInput.value);
    const feet = meters * METERS_TO_FEET;
    feetInput.value = feet.toFixed(2);
  }

  function convertFeetToMeters() {
    const feetInput = document.getElementById("feetInput");
    const metersInput = document.getElementById("metersInput");

    const feet = parseFloat(feetInput.value);
    const meters = feet * FEET_TO_METERS;
    metersInput.value = meters.toFixed(2);
  }
</script>

Length Unit Converter



Explanation:

Using html, I am able to style the buttons to have space between them. I am also able to create two inputs and corresponding buttons.

Javascript allows me to actually create the functions for the conversions. I use const to define the conversion constants (1 meter = 3.28084 feet, and 1 foot= 0.3048 meter) which I can use in my functions.

The javascript gets the input values by getElementById with the ids for the forms. ParseFloat makes sure the inputs are floating point numbers (can be used for calculations). The input values are now ready to be multiplied by their conversion constant to get meters/feet that are equivalent. The toFixed(2) allows the number to be rounded to two decimal places.

The metersInput.value and the feetInput.value with the toFixed updates the input field to have the new conversion value.