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

Iai*_*der 63 javascript jquery decimal-point rounding number-formatting

这就是我现在所拥有的:

$("#number").val(parseFloat($("#number").val()).toFixed(2));
Run Code Online (Sandbox Code Playgroud)

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

meo*_*ouw 100

如果你在几个领域这样做,或经常这样做,那么也许一个插件就是答案.
这是一个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">
Run Code Online (Sandbox Code Playgroud)


svi*_*nto 62

也许是这样的,如果你愿意,你可以选择多个元素?

$("#number").each(function(){
  $(this).val(parseFloat($(this).val()).toFixed(2));
});
Run Code Online (Sandbox Code Playgroud)

  • 另外,你的dom中不应该有重复的id.考虑将'number'更改为类. (22认同)