W jQuery, jaki jest najlepszy sposób formatowania liczby do 2 miejsc po przecinku?

Oto co mam teraz:

$("#number").val(parseFloat($("#number").val()).toFixed(2));
Wygląda mi to na bałagan. Nie sądzę, żebym łączył funkcje poprawnie. Czy muszę ją wywoływać dla każdego pola tekstowego, czy mogę utworzyć osobną funkcję?
Author: random, 2009-01-25

3 answers

Jeśli robisz to do kilku pól, lub robi to dość często, to być może Plugin jest odpowiedzią.
Oto początki wtyczki jQuery, która formatuje wartość pola do dwóch miejsc po przecinku.
Jest on wyzwalany przez zdarzenie onchange pola. Możesz chcieć czegoś innego.

<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">
 106
Author: meouw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-25 21:33:39

Może coś takiego, gdzie można wybrać więcej niż jeden element, jeśli chcesz?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});
 64
Author: svinto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-26 09:14:12

Modyfikujemy funkcję Meouw do użycia z keyup, ponieważ gdy używasz danych wejściowych, może ona być bardziej pomocna.

Sprawdź to:

Hej!@ heridev i ja stworzyliśmy małą funkcję w jQuery.

Możesz spróbować dalej:

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

​ DEMO ONLINE:

Http://jsfiddle.net/c4Wqn/

(@heridev, @ vicmaster)

 4
Author: vicmaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-27 16:57:51