Javascript : function checking if the answer to score as a percentage has more than 2 decimal places
<p>I want to create a dynamic worksheet for my students, so every time they do it they see different questions. The question that I am trying to create ie, calculate the percentage if I scored X out of a total of Y.</p>

<p>Here are the 3 functions which work together, the first generates some numbers, calls the second, which in turn calls the third to check if it more than 2 decimal places, then if it is, the second creates a new SCORE number which repeats until it finds an answer which is 2 decimal places or less, then returns the SCORE number which works to the first, which outputs it.</p>

<p>I keep getting one of three outputs : undefined where the SCORE should be, no output at all, or a working question.</p>

<p>I cannot understand how it works sometimes, throws undefined sometimes and gives completely nothing at other times.</p>

<p>Any ideas.</p>

<pre><code>function scorePercent()
{
    var output="";
    var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
    output = output + "&lt;div&gt;A score of " + chkScore(score,total) + " out of " + total + ".&lt;/div&gt;&lt;/br&gt;";

    document.getElementById("qOut").innerHTML=output;

}

function chkScore(n1,n2)
{
    var answ = (n1/n2)*100;
    if(dps(answ)&gt;2)
    {
        var scoreNew = Math.floor((Math.random()*(n2-1))+1);
        chkScore(scoreNew, n2);
    }
    else
    {
        return n1;
    }       
}

function dps(num) 
{
    var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
    if (!match) { return 0; }
    return Math.max(
            0,
        // Number of digits right of decimal point.
            (match[1] ? match[1].length : 0)
        // Adjust for scientific notation.
         - (match[2] ? +match[2] : 0));
}
</code></pre>
