5

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 instead. The solution is easy ( How do I add an integer value with javascript (jquery) to a value that's returning a string?, How to make an addition instead of a concatenation) if your number is always in integer. However my string could be a float or an integer, and at the time of the addition, and I don't know which it will be. Is there a way to make sure the addition happens regardless of whether it's a float or integer?

Community
  • 1
  • 1
dnc253
  • 39,967
  • 41
  • 141
  • 157

4 Answers4

10

Try using parseFloat. The input variables will be converted to floats, which will work whether the string contains an integer or a float. Your result will always be a float.

kitti
  • 14,663
  • 31
  • 49
  • So, I was worried that if I used `parseFloat()` I'd end up with "5.0" instead of "5", but apparently that's not the case? – dnc253 Oct 19 '12 at 20:47
  • 1
    `parseFloat('5') == 5`, `parseFloat('5.11') == 5.11` (in Chrome at least) – kitti Oct 19 '12 at 20:49
  • Floating point, so it won't force a certain number of digits down your throat. – Asad Saeeduddin Oct 19 '12 at 21:15
  • Worked perfectly for me; I was reading values from an input field and performing a complex function, but when X was == 1, then all hell broke loose in the function (a*x^2+bx+c with c=0 was causing the result to be ten times to large, as "0" was being concatenated to the end, rather than the value of zero being added to the result) – jedison Dec 13 '14 at 05:44
4

It is reasonably safe to always use parseFloat even if you are given an integer. If you must use the appropriate conversion, you could match for a decimal point and use the appropriate function.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
2

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.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • Surely better to return NaN if either is NaN ? – Lee Taylor Oct 19 '12 at 20:46
  • idk, what's the spec? ;-) ... You should be concerned with NaN cos it'll bite you in the arse first chance it gets. – jcolebrand Oct 19 '12 at 20:53
  • There's a problem with this, which is that ```true + 2``` returns 3, but ```parseFlaot(true) + parseFloat(2)``` returns NaN. I mean if you don't care about adding bools then it isn't a problem but that's why I'm here. – Casey Oct 30 '14 at 21:26
  • How does that work with my second solution? Seems like my second solution does basically what you're worried about ... – jcolebrand Nov 13 '14 at 20:12
  • Doesn't quite work as expected; that function with 2 and true returns 2 when I'd expect 3. I just ended up testing for `input === true` or `input === false`. – Casey Nov 17 '14 at 16:26
  • But ... why would 2 + true = 3? – jcolebrand Nov 19 '14 at 03:23
  • Open up a JavaScript console and try it. `true + 2` will return 3. True is coerced to 1 and false to 0 in all numeric operations. Excel also exhibits the same behavior, FWIW, but I don't know other examples. – Casey Nov 19 '14 at 14:52
  • As for why it matters to me, I'm dealing with transforming user input into JS and wanted to be consistent, even if the behavior is of limited utility. – Casey Nov 19 '14 at 14:55
  • So, here's the deal ... my example above (and the entire premise of the question) is that you're trying to only add numbers together. If you wanted to do something where booleans were counted as 1, you could add a check for that. The issue is that bools cast to 1 or 0, but "this is a truthy string" is also boolean truthy, so you would have to match on precisely true, and not just "TRUE". I don't know your requirements, but this problem on this page is obviously not your problem. You have a different issue. – jcolebrand Nov 19 '14 at 16:25
  • As you can see from my previous comment, that's what I did. The goal of my comment was really to point out this issue to anyone who cares about it and is reading this answer. I actually did have the problem described in the OP, except I also cared about the behavior with boolean input and the methods you're describing lead (depending) to either NaN or incorrect results in that case. I'm trying to add information, not seek help. There's no need to get defensive. – Casey Nov 19 '14 at 17:19
  • "Doesn't work as expected" implies it's broken. I want my code to be as clean and bug-free and side-effect free as possible. "This code does not work for me in this case" is a bad comment for me to see. I naturally want to fix my code. Then to find out "yes, but I want this to do something entirely else" makes me go "well then what did you expect, that wasn't on the tin". I've breathed, walked away, and have no other concerns ;-) – jcolebrand Nov 19 '14 at 20:35
0

For some reason.... who knows???

Using parseFloat works.... when parseInt does not... obviously they are not always the same.

FWIW.... I'm "adding" data elements from "checked" checkboxes here...

    var AddOns = 0;

    $( '.broadcast-channels').each(function(){              
        if ( $(this).prop("checked")) {                             
            var thisAddOn =  parseFloat($(this).data('channel'));      
            AddOns = AddOns + thisAddOn;                                      
        }           
});
Bill Warren
  • 392
  • 8
  • 11