Search code examples
javascriptcalculatorscientific-notationinfinity

Scientific notation with infinity rule disabled


I keep trying to make my result in scientific notation and still have the infinity rule outlawed, but I can't seem to get it to work. When I use the toExponential() function, it responds with an error message. Please may I have some help? Here is the code:

<!DOCTYPE html>
<html>
<body>
Base:<input id="n1" rows=1 cols=3 type=number">
Exponent:<input id="n2" rows=1 cols=3 type="number">
<script>
var calc=0
function calculate() {
   calc=document.getElementById("result").innerHTML = 
   BigInt(document.getElementById("n1").value)**BigInt(document.getElementById("n2").value)
   calc.toExponential()=document.getElementById("result");
}
   </script>
   <button onclick="calculate()">Calculate</button><p>=<span id="result" style=display:none></span> 
   </p>
   <script src="decimal.js/decimal.js"></script>
   </body>
   </html>

Solution

  • toExponential doesn't exists on BigInt. Since toExponential() exists in Number.prototype.toExponential(), you need to parse BingInt to float and then call toExponential().

    function calculate() {
      let calc = BigInt(document.getElementById("n1").value)**BigInt(document.getElementById("n2").value);
      document.getElementById("result").innerHTML = parseFloat(calc).toExponential();
      console.log(parseFloat(calc).toExponential());
    }
    <!DOCTYPE html>
    <html>
    <body>
    Base:<input id="n1" rows=1 cols=3 type=number">
    Exponent:<input id="n2" rows=1 cols=3 type="number">
       <button onclick="calculate()">Calculate</button><p>=<span id="result"></span> 
       </p>
       
       </body>
       </html>