如何在输入时为输入字段中的数字添加自动小数

时间:2012-06-15 02:41:49

标签: jquery

我试图在输入数字时自动更改为decimel的输入,但仅限于2个decimel点。请帮帮我,因为即时通讯仍然是新的jquery

我的代码:

 $.fn.billFormat = function() {
        $(this).keyup( function( e ){
                if( isNaN(parseFloat(this.value )) ) return;
                this.value = parseFloat(this.value).toFixed(2);
        });
        return this; 
 }

$('#ENQUIRY_PREPAIDBILL .bill_issued').billFormat();

我希望输出像这样

0.00< ------默认值
0.01< ------打字1
0.10< ------输入0
1.00< ------输入0

2 个答案:

答案 0 :(得分:2)

 $.fn.billFormat = function() {
        this.val("0.00");
        this.keyup( function( e ){
                if( isNaN(parseFloat(this.value )) ) return;
                this.value = parseFloat(this.value * 10, 10).toFixed(2);
        });
        return this; 
 }

这是demo

答案 1 :(得分:0)

这是另一个不用担心溢出的解决方案(你可以找到demo here

$(document).ready(function(){
    $('#txtInput').keydown(function(e){
        var value = $('#txtInput').val().toString();
        var number = null;
        if(value == '')
            value = '0.00';
        switch(e.which)
        {
            case 48:
            case 49:
            case 50:
            case 51:
            case 52:
            case 53:
            case 54:
            case 55:
            case 56:
            case 57:
                number = e.which - 48;
            case 8:
            case 46:
            case 32:
            case 37:
            case 38:
            case 39:
            case 40:
                break;
            default:
                e.preventDefault();
                break;
        }
        var dotIndex = value.indexOf('.');
        if(number === null)
        {
            value = value.substr(0,dotIndex-1) + '.' + value.substr(dotIndex -1,1) + value.substr(dotIndex+1,1);
            if(value.indexOf('.') ==0)
            {
                value = '0' + value;
            }
        }
        else
        {

            value = value.substr(0,dotIndex) + value.substr(dotIndex+1,1) + '.' + value.substr(dotIndex+2);

            value += number.toString();  
            value = value.replace(/^0+/,'');
            if(value.indexOf('.') == 0)
            {
                value = '0' + value;
            }               

        }
        $('#txtInput').val(value);
        e.preventDefault();
    }).keyup(function(e){

        switch(e.which)
        {
            case 48:
            case 49:
            case 50:
            case 51:
            case 52:
            case 53:
            case 54:
            case 55:
            case 56:
            case 57:
                e.preventDefault();
                break;
        }
    });
});​

和此代码的html

<input type='text' id='txtInput' />​