Format currency input with 1000 separator and 2 decimal places upon typing using jQuery/JS?

前端 未结 3 1563
名媛妹妹
名媛妹妹 2021-01-07 08:25

I have a text input where I want it to format while typing a value allowing 2 decimal places and 1000 separators. It should only allow digits. I have done the following but

3条回答
  •  隐瞒了意图╮
    2021-01-07 09:08

    $('#price').on('keyup click change paste input', function (event) {
        $(this).val(function (index, value) {
            if (value != "") {
                //return '$' + value.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                var decimalCount;
                value.match(/\./g) === null ? decimalCount = 0 : decimalCount = value.match(/\./g);
    
                if (decimalCount.length > 1) {
                    value = value.slice(0, -1);
                }
    
                var components = value.toString().split(".");
                if (components.length === 1)
                    components[0] = value;
                components[0] = components[0].replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                if (components.length === 2) {
                    components[1] = components[1].replace(/\D/g, '').replace(/^\d{3}$/, '');
                }
    
                if (components.join('.') != '')
                    return '$' + components.join('.');
                else
                    return '';
            }
        });
    });
    

提交回复
热议问题