0

this function is working properly but i dnt wan to round of my number..this function round of my number.

jquery( 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
    });
});
  • 1
    If the function does something that you don't want, then it is *not* working properly… – Bergi Jun 05 '14 at 02:17
  • Have you written this yourself? Do you understand what it does? Where is your problem with fixing the functionality? – Bergi Jun 05 '14 at 02:18
  • note that unless you've done something hinky, jQuery is spelled, well like that – adeneo Jun 05 '14 at 02:18
  • `return this; //for chaining` is rubbish inside the event handler and can be omitted. – Bergi Jun 05 '14 at 02:19
  • @Bergi - oh no, chaining is important, one should always return this and not that. – adeneo Jun 05 '14 at 02:19
  • The question itself is worded wrong. Please change it. – Ali Gajani Jun 05 '14 at 02:21
  • Here's a protip, if you don't want to round the numbers remove the entire code, as that's all it does, round the number to two decimal places. – adeneo Jun 05 '14 at 02:23

2 Answers2

0

Change a little your code. Remove the .toFixed(2) and add a regular expression to keep only the 2 digits after the punkt.

/(\d+\.\d{2})/i

\d+ this gets the first digits before punkt, \. this is the punkt, \d{2} this only takes 2 digits and by using the () we can get the code on the second index of the array so we get the item [1]. We apply the regular expression with the .match method. More about regular expression here.

So here is the code:

$( function() {
    $('.two-digits').keyup(function(){
        if($(this).val().indexOf('.')!=-1){         
            if($(this).val().split(".")[1].length > 2){
                if( isNaN( parseFloat(this.value.match(/(\d+\.\d{2})/i)[1])) ) return;
                this.value = parseFloat(this.value.match(/(\d+\.\d{2})/i)[1]);
            }  
         }            
         return this;
    });
});

Example: http://jsfiddle.net/A24YA/1/

DarkThanos
  • 122
  • 4
-1

You can use this

Math.floor(this.value * 100) / 100
Mr.Cocococo
  • 1,401
  • 2
  • 11
  • 13