Quadratic equation in ECMAScript

Example for versions SpiderMonkey 1.7

The example is meant to be executed from the web-browser. To run the example, copy the code to a file quadratic.js and create an HTML file placed in the same directory and containing the following text:

<script type="text/javascript" src="quadratic.js"></script>
<form name="quadratic">
    <input type="number" required="required" name="A">
    <input type="number" required="required" name="B">
    <input type="number" required="required" name="C">
    <input type="button" value="Solve" onClick="solve()">
<p id="output">

This will create a web-page with three input fields and a button. The equation will be solved once the button is pressed, and the roots will be printed beneath the inputs.

JavaScript doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.

function print(real, imag) 
{   if (Math.abs(imag)<1E-6)
        return real;
        return '('+real+','+imag+')';

function solve() 
{   A = document.quadratic.A.value;
    if (Math.abs(A)<1E-3)
    {   document.getElementById('output').innerHTML = 'Not a quadratic equation';
    B = document.quadratic.B.value;
    C = document.quadratic.C.value;
    A = 2*A;
    D = B*B-2*A*C;
    if (Math.abs(D)<1E-3)
    {   document.getElementById('output').innerHTML = 'x = '+(-B/A);
    if (D>0)
        document.getElementById('output').innerHTML = 'x1 = '+print((-B+Math.sqrt(D))/A, 0)+'<br />x2 = '+print((-B-Math.sqrt(D))/A, 0);
        document.getElementById('output').innerHTML = 'x1 = '+print(-B/A,Math.sqrt(-D)/A)+'<br />x2 = '+print(-B/A,-Math.sqrt(-D)/A);