72

This is what I have right now:

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

It looks messy to me. I don't think I'm chaining the functions correctly. Do I have to call it for each textbox, or can I create a separate function?

random
  • 9,774
  • 10
  • 66
  • 83
Iain Holder
  • 14,172
  • 10
  • 66
  • 86
  • Possible duplicate of [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – Liam Aug 06 '18 at 15:28

3 Answers3

110

If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.

<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">
meouw
  • 41,754
  • 10
  • 52
  • 69
66

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});
C.OG
  • 6,236
  • 3
  • 20
  • 38
Svante Svenson
  • 12,315
  • 4
  • 41
  • 45
  • 23
    On a side note you shouldn't have duplicate ids in your dom. Consider changing 'number' to a class. – gradbot Jan 25 '09 at 17:51
  • 1
    @gradbot - nothing about this implies that there is more than one element with id = "number". It looks like svinto is just using the "each" function as a way to reduce the number of times the magic string "#number" appears in the code. It is a small (and good, I think) improvement on LainMH's code. If this formatting only needs to be done on one page, then this is the way I would prefer to do it. If it needs to be duplicated on more than one page, then I prefer meouw's plugin approach - except extracted out to an external javascript file. – Daniel Schilling Mar 29 '11 at 18:58
  • @DanielSchilling..I assume what gradbot was trying to say was that if you want to apply the same function over multiple input box on a single page then too you cannot provide them the same id or you cannot keep on mentioning every input box's id like this `('#num1,#num2').each(function(){});` .So it would be better to use class approach like this `('.number').each(function(){});`.And provide each input box with a common class -number – payal_suthar Oct 06 '16 at 11:30
4

We modify a Meouw function to be used with keyup, because when you are using an input it can be more helpful.

Check this:

Hey there!, @heridev and I created a small function in jQuery.

You can try next:

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)

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
vicmaster
  • 97
  • 3