JSFiddle - React, Tailwind, and code Playground

by Jordan Enev

HTML

<script src="https://cdn.ethers.io/lib/ethers-5.6.9.umd.min.js"
        type="application/javascript"></script>

<div>USD:</div>
<input type="text" name="amount" />
<hr />
<div>ETH output:</div>
<div id="eth"></div>

JavaScript

const convert = (input) => {
  // Define the values
  const pricePerETH = 3800.20;
  const inputAmountUSD = input.target.value;
  
  // Define scaling factors
  const priceFactor = 100n; // Scaling factor for 2 decimal places in pricePerETH
  const amountFactor = 1_000_000_000_000_000_000n; // Scaling factor for 18 decimal places in inputAmountUSD

	console.log({ priceFactor, amountFactor })

  // Convert to BigInt
  const BIpricePerETH = BigInt(Math.round(pricePerETH * Number(priceFactor)));
  const BIinputAmountUSD = BigInt(Math.round(inputAmountUSD * Number(amountFactor)));
  
  console.log({BIpricePerETH, BIinputAmountUSD})

  // Perform the division
  const resultBigInt = (BIinputAmountUSD * priceFactor) / BIpricePerETH;
  
  console.log({ resultBigInt })

  // UI
  const resultString = ethers.utils.formatUnits(resultBigInt, 18); // 18, because of amountFactor
  
  document.getElementById('eth').innerHTML = resultString
}

document.getElementsByName("amount")[0].addEventListener('input', convert)