How to ensure javascript addition instead of string concatenation (Not always adding integers)

前端 未结 4 1365
野的像风
野的像风 2020-12-11 19:16

Through my javascript library, I end up with a string that represents a number. Now I want to preform an addition on that number without it doing a string concatenation inst

4条回答
  •  甜味超标
    2020-12-11 19:47

    I'm going to assume that float addition is sufficient, and if it isn't, then you'll need to dig deeper.

    function alwaysAddAsNumbers(numberOne, numberTwo){
      var parseOne = parseFloat(numberOne),
          parseTwo = parseFloat(numberTwo);
      if (isNaN(parseOne)) parseOne = 0;
      if (isNaN(parseTwo)) parseTwo = 0;
      return parseOne + parseTwo;
    }
    

    To take what @Asad said, you might want to do this instead:

    function alwaysAddAsNumbers(a, b){
      var m = 0,
          n = 0,
          d = /\./,
          f = parseFloat,
          i = parseInt,
          t = isNaN,
          r = 10;
      m = (d.test(a)) ? f(a) : i(a,r);
      n = (d.test(b)) ? f(b) : i(b,r);
      if (t(m)) m = 0;
      if (t(n)) n = 0;
      return m + n;
    }
    

    this will always give you at least a zero output, and doesn't tell you if either one is NaN.

提交回复
热议问题