【问题标题】:In jQuery, what's the best way of formatting a number to 2 decimal places?在 jQuery 中,将数字格式化为 2 位小数的最佳方法是什么?
【发布时间】:2010-10-03 10:27:37
【问题描述】:

这就是我现在拥有的:

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

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

【问题讨论】:

标签: javascript jquery rounding decimal-point number-formatting


【解决方案1】:

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

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

【讨论】:

  • 附带说明,您的 dom 中不应有重复的 id。考虑将“数字”更改为类。
  • @gradbot - 这并不意味着存在多个 id = "number" 的元素。看起来 svinto 只是使用“each”函数来减少魔术字符串“#number”出现在代码中的次数。这是对 LainMH 代码的一个小的(我认为很好)的改进。如果这种格式只需要在一页上完成,那么这就是我更喜欢的方式。如果它需要在多个页面上复制,那么我更喜欢 meouw 的插件方法 - 除了提取到外部 javascript 文件。
  • @DanielSchilling..我假设 gradbot 想说的是,如果您想在单个页面上的多个输入框上应用相同的功能,那么您也不能为它们提供相同的 ID,或者您不能继续提到每个输入框的id,像这样('#num1,#num2').each(function(){});。所以最好使用像这样('.number').each(function(){});这样的类方法。并为每个输入框提供一个通用的类-编号
【解决方案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">

【讨论】:

  • 嗨,我想知道我们是否需要另一个插件到 currencyFormat()?..
【解决方案3】:

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

【讨论】:

  • 我想你可能想用 .change() 代替 .keyup()...
猜你喜欢
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
相关资源
最近更新 更多