简体   繁体   中英

Numbers with commas in Javascript

I have a javascript function that accepts a number and performs a mathematical operation on the number. However, the number I'm passing in could have a comma in it, and from my limited experience with Javascript I am having problems working with that value. It doesn't seem to treat that as a numeric type.

What's the easiest way to take a parameter with a value of 1,000 and convert it to a numeric 1000?

You can set up your textbox to have an onblur() function so when the user attempts to leave the textbox, you then remove the commas from the value by using the javascript replace function

example :

  function checkNumeric(objName)
  {
    var lstLetters = objName;

    var lstReplace = lstLetters.replace(/\,/g,'');
  }  

With input tag here:

<input type="text" onblur="checkNumeric(this);" name="nocomma" size="10" maxlength="10"/>

A quick and dirty way is to use the String.replace() method:

var rawstring = '1,200,000';
var cleanstring = rawstring.replace(/[^\d\.\-\ ]/g, '');

This will set cleanstring to: 1200000 . Assuming you are using US formatting, then the following conversions will occur:

1234 --> 1234
1,234 --> 1234
-1234 --> -1234
-1,234 --> -1234
1234.5 --> 1234.5
1,234.5 --> 1234.5
-1,234.5 --> -1234.5
1xxx234 --> 1234

If you are in other locales that invert the '.' and ',', then you'll have to make that change in the regex.

Converts comma delimited number string into a type number (aka type casting )

+"1,234".split(',').join('') // outputs 1234

Breakdown :

+             - math operation which casts the type of the outcome into type Number
"1,234"       - Our string, which represents a comma delimited number
.split(',')   - split the string into an Array: ["1", "234"], between every "," character
.join('')     - joins the Array back, without any delimiter: "1234"

And a simple function would be:

function stringToNumber(s){
  return +s.split(',').join('');
}

Just replace all the commas with a blank.

You can follow this: http://blog.techsaints.com/2007/06/25/javascript-how-to-remove-all-commas-from-a-number/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM