Adeel Aslam
Adeel Aslam

Reputation: 1294

text box decimal format fixing

I have a simple text box and I am entering number value to this.And i want to format the number value to two decimal places.Like If i enter the 10 in the text box and after pressing entering or leaving textbox it should be converted into 10.00.Please tell me if there exist any possibility to do this using javascript or vb.net or asp.net property of textbox.I already tried in JavaScript on enter key or tab key press but it convert it into 10.00 each time when i press the enter or tab.here is code

//Make Formatting with .00


document.onkeydown = function disableKeys() {

    if( typeof event != 'undefined' ) {
      if( (event.keyCode == 9) ||
          (event.keyCode == 13) ) {
          var a;
          var b;
          a=parseFloat(document.getElementById('txtpkrusd').value,10);
          b=parseFloat(document.getElementById('txtRatelb').value,10);
          document.getElementById('txtpkrusd').value=formatNumber(a);         
          document.getElementById('txtRatelb').value=formatNumber(b);         

      }
    };
};

Upvotes: 1

Views: 9576

Answers (2)

Tats_innit
Tats_innit

Reputation: 34107

hiya hope this helps: (apart from my comment above i.e. to round use .toFixed(num))

demo (enter the number and press enter) : http://jsfiddle.net/6wG26/5/ OR Enter and Tab keys both here http://jsfiddle.net/Mtw7c/7/

Please; let me if this is not what you want I will delete my post; but this will help you.

Since you dint had much code up I have made forked sample here:

**HTML:**

<input type="text" name="one" class="currency">


**JQuery code:**

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


    $( function() {
        $('.currency').currencyFormat();
    });​

OR ENter key & Tab key here: http://jsfiddle.net/Mtw7c/7/

 $('.currency').live('keydown', function(e) { 
        var key = e.keyCode || e.which; 

          if (key== 9 || key == 13) { 
            e.preventDefault(); 
              if( isNaN( parseFloat( this.value ) ) ) return;
                    this.value = parseFloat(this.value).toFixed(2);
            // call custom function here
          }         

    });

hope this helps and it will be good if you read the following link - sample taken from here but to make it sample for you, In jQuery, what's the best way of formatting a number to 2 decimal places?

You can always put validation for the number only text box & other amendments, Hope this helps mate, cheers!!

Upvotes: 1

dhinesh
dhinesh

Reputation: 4764

var num = 10;

var result = num.toFixed(2);  //will give 10.00

Examples

Upvotes: 2

Related Questions