In jQuery, what's the best way of formatting a number to 2 decimal places?

前端 未结 3 1012
难免孤独
难免孤独 2020-11-27 13:59

This is what I have right now:

$(\"#number\").val(parseFloat($(\"#number\").val()).toFixed(2));

It looks messy to me. I don\'t think I\'m

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 14:56

    We modify a Meouw function to be used with keyup, because when you are using an input it can be more helpful.

    Check this:

    Hey there!, @heridev and I created a small function in jQuery.

    You can try next:

    HTML


    jQuery

    // apply the two-digits behaviour to elements with 'two-digits' as their class
    $( function() {
        $('.two-digits').keyup(function(){
            if($(this).val().indexOf('.')!=-1){         
                if($(this).val().split(".")[1].length > 2){                
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                }  
             }            
             return this; //for chaining
        });
    });
    

    ​ DEMO ONLINE:

    http://jsfiddle.net/c4Wqn/

    (@heridev, @vicmaster)

提交回复
热议问题