Christopher Allen Christopher Allen - 5 months ago 33
Node.js Question

Im using node.js, and im trying to add two integers, however, they just put them together

Im using node.js, and im trying to add two integers, however, they just put them together...
Iv looked up Float, trying to float the integers, but node.js doesnt recognize float.

Answer

Apparently at least one of both is actually a string containing a number. V8 then does string concatenation instead of adding the numbers.

What you need to do is to convert the strings to real numbers. You cam do that using the parseInt() or parseFloat() functions, but a faster way is to subtract 0: As subtracting from a string is not possible, V8 tries to treat the content of the string as a number.

In the end you also get a number, but AFAIK this method is faster than using the parse functions.

Example:

var foo = '23';
typeof (foo - 0); // => 'number'

var a = '23',
    b = '42';
console.log((a - 0) + (b - 0)); // 65
Comments