How to Round Numbers(Decimal)

How to round a number to a specified number of decimal places

by Avinashullal

HTML

<form name="roundform">
    <table border="0" cellspacing="0" cellpadding="5">
        <tr>
            <tdhttp://jsfiddle.net/Avinashullal/SkNtj/#update>Round:</td>
                <td>
                    <input id="numberfield" name="numberfield" type="text" value="31.78">to
                    <input id="decimalfield" name="decimalfield" type="text" value="2" size="3">decimal places</td>
        </tr>
        <tr>
            <td>Result:</td>
            <td>
                <input id="result" name="roundedfield type=" text "" value="">
                <input type="button" id="calculate" value="Calculate" onClick="">
            </td>
        </tr>
    </table>
</form>

JavaScript

function roundNumber(number, decimals) {
    var newnumber = new Number(number + '').toFixed(parseInt(decimals));
    return parseFloat(newnumber);
}

$(document).ready(function () {
    $('#calculate').click(function () {
        var n = $('#numberfield').val();
        var d = $('#decimalfield').val();
        $('#result').val(roundNumber(n, d));
    });
});