繁体   English   中英

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

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

这就是我现在所拥有的:

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

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

如果您对多个领域这样做,或者经常这样做,那么也许插件就是答案。
这是一个 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">

也许像这样,如果您愿意,您可以选择多个元素?

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

我们修改了一个 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM