How to round a number up and add numeric punctuation

162 views Asked by At

I've got the following pen: http://codepen.io/anon/pen/LVLzvR

I cant quite figure out how to round the number up so you don't break the punctuation. I need to round the number up as I don't want to see a value like 33,333.,333

 //ADDS PUNCTUATION EVERY THREE CHARACTERS
  $('input.numericpunctuation').keyup(function(event){

      var oNum= $(this).val(); // USE THIS NUMBER FOR CALCULATION

      var num = oNum.replace(/,/gi, "").split("").reverse().join("");

      var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));

      console.log(num2);
      console.log(oNum);

      // the following line has been simplified. Revision history contains original.
      $(this).val(num2);
  });

function RemoveRougeChar(convertString){


    if(convertString.substring(0,1) == ","){

        return convertString.substring(1, convertString.length)            

    }
    return convertString;

}

Example input event: If I input 5555, is expect to see (and do see) 5,555. However if I add 5555.55 I get 5,555,.55. Ideally id like to round the number up removing the decimal.

1

There are 1 answers

3
avnr On BEST ANSWER

The problem isn't just with decimals, you will get the wrong formatting also by entering non digits, e.g., clicking King Kong will result in Kin,g K,ong. So, what you probably want is to filter out non-digits, which can be done by changing the line var oNum= $(this).val(); to:

var oNum= $(this).val().match(/\d/g).join('');

The value inside the match function is a RegEx object - if you never used it before then congratulations!