Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse a number but keep the negative's in a text box

Here is what I’m trying to do.

Right now I can parse a number by adding commas automatically, however, when I try to type a negative it goes away.

Here is the current code that I’m using to parse the number:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      $(this).val(function(index, value) {
          return value
                .replace(/\D/g, "")
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }); 

How do I keep the number negative value?

>Solution :

\D matches anything that isn’t a decimal digit, so you’re removing the minus sign. Use [^-\d] instead to remove anything that isn’t a digit or minus sign.

function add_commas(value) {
  return value
    .replace(/[^-\d]/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

console.log(add_commas('1234567'));
console.log(add_commas('-1234567'));
console.log(add_commas('-123,4X567'));

Caveat: this won’t work correctly if they put a - in the middle of the number, since it will be left in the number.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading