skip to Main Content

I’m developing a JavaScript calculator and facing an issue with the division operation. When very small numerators are divided by large denominators, the result becomes "0". This isn’t the desired behavior. Ideally, the calculator should either:

  • Display a more informative message (e.g., "Number too small to divide").
  • If possible, overcome this limitation and continue dividing.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Approaching Zero</title>
</head>
<body>
    <script>
        const result = 1.2e-321 / 99999999999999;
        console.log(result);
    </script>
</body>
</html>

I thought it would continue processing despite how small it is, but it turns out it’s not enough for precision and accuracy.

2

Answers


  1. Maybe you can try somthing like that:

    function decomp(n) {
        let exp=0; 
        while(n<1|n>10){
            if(n<1){n*=10;exp++;}
            else if(n>10){n/=10;exp--;}
            else return [n, exp];
        }
    }
    function division(n, d) {n=decomp(n);d=decomp(d);return [n[0]/d[0], n[1]/d[1]]}
    
    Login or Signup to reply.
  2. as Iłya outlined in the comment, this issue comes from the fundamental flaw of JS handling binary floating-point operations. As outlined in the related question.

    If you want your calculations to be precise you can achieve it via a few ways:

    • changing the datatype
    • performing calculations with integers and accounting for decimals with precision
      • example: a user inputs 1, your internal code, would track the number as 1 * 10^36 (up to 36 decimal points)

    Personally, I solved this issue with a use of an external JS library called JS Big Decimal. This would allow you to store numbers in string format and perform basic operations with them, like:

    • addition,
    • subtraction,
    • multiplication,
    • division,
    • equation.

    A few notes for the approach:

    • This approach might not be optimal for database storage unless in specific cases, where precision is required over storage space.
    • You would need to develop functions for more advanced options such as:
      • raising to the power
      • taking a root of a number
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search