3

Anyone know how I can get the following to limit the decimals to 2 places? There's also a problem that it displays NaN when there are no values in the two fields (I'd rather it just show nothing). Can anyone help fix these problems?

HTML

<td class="grade">
    <input type="text" value="28" class="numerator" /> / <input type="text" value="30" class="denominator" />
    <div class="result"></div>
</td>

jQuery

function update($ele) {
    var n = Number($ele.find('.numerator')[0].value);
    var d = Number($ele.find('.denominator')[0].value);
    $ele.find('.result').text(n / d * 100);
}

$('.grade').each(function() {
    update($(this));
});

$('.grade input').on('keyup', function() {
    update($(this).closest('.grade'));
});
Jeremy Blazé
  • 155
  • 1
  • 8

1 Answers1

3

fiddle:

function update($ele) {
    var n = Number($ele.find('.numerator')[0].value);
    var d = Number($ele.find('.denominator')[0].value);
    /* this works but is slightly more verbose (and maybe a bit slower) */
    var val = (n / d * 100);
    $ele.find('.result').text(( isNaN(val) || ! isFinite(val) ) ? '' : val.toFixed(2));
    /* This might be faster, and also make everything a bit more succinct * /
    var val = d !== 0 ? n / d * 100 : NaN;
    $ele.find('.result').text(isNaN(val) ? '' : val.toFixed(2));
    /* */
}
kalley
  • 16,448
  • 2
  • 34
  • 35