Thursday, July 31, 2014

javascript round decimal to preferred number of decimal places

function round(value, decimals) {
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}

javascript validation for decimal(10,2)

$(function () {
    $('.decimal10n2').keyup(function () {
        if (!$(this).val().match(/./gi) || !$(this).val().match(/[0-9]+/g)) {
            $(this).val("");
        }
        else if ($(this).val().split('.').length - 1 > 1)
        {
            this.value = $(this).val().slice(0, -1);
        }
        else if ($(this).val().indexOf('.') != -1) {
            if($(this).val().split(".")[0].length > 10)
            {
                if (isNaN(parseFloat(this.value))) return;
                this.value = $(this).val().split(".")[0].slice(0,-1);
            }
            else if ($(this).val().split(".")[1].length > 2) {
                if (isNaN(parseFloat(this.value))) return;
                this.value = parseFloat(this.value).toFixed(2);
            }
        }

        return this;
    });
});