在jQuery中,将数字格式化为2个小数位的最佳方法是什么?

问题描述 投票:63回答:3

这是我现在拥有的:

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

对我来说看起来很乱。我认为我没有正确地链接功能。我必须为每个文本框调用它,还是可以创建一个单独的函数?

javascript jquery rounding decimal-point number-formatting
3个回答
101
投票

如果您要在多个领域进行此操作,或者经常这样做,那么答案可能就是插件。这是jQuery插件的开头,该插件将字段的值格式化为两位小数。它由字段的onchange事件触发。您可能想要其他东西。

<script type="text/javascript">

    // mini jQuery plugin that formats to two decimal places
    (function($) {
        $.fn.currencyFormat = function() {
            this.each( function( i ) {
                $(this).change( function( e ){
                    if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
                });
            });
            return this; //for chaining
        }
    })( jQuery );

    // apply the currencyFormat behaviour to elements with 'currency' as their class
    $( function() {
        $('.currency').currencyFormat();
    });

</script>   
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">

63
投票

也许是这样,如果需要,您可以在其中选择多个元素?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

4
投票

我们修改了Meouw函数以用于keyup,因为当您使用输入时,它可能会更有帮助。

检查此:

嘿,@ heridev,我在jQuery中创建了一个小函数。

您可以尝试下一个:

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">​

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
    });
});

在线演示:

http://jsfiddle.net/c4Wqn/

((@ heridev,@vicmaster)

© www.soinside.com 2019 - 2024. All rights reserved.