簡體   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