Numbers with commas in Javascript

后端 未结 4 1359
無奈伤痛
無奈伤痛 2020-12-24 08:02

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 fr

4条回答
  •  被撕碎了的回忆
    2020-12-24 08:23

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

提交回复
热议问题