2

This is my first day learning Node and I'm trying to implement a program that returns the sum to N numbers where N is the input. I am using Ubuntu 14.04 with Node installed using the package manager (v0.10.25). Here is my code

var myNumber = process.argv[2]
var sumToMyNumber =  myNumber*(myNumber+1)*0.5
console.log(sumToMyNumber)

The program file is SumToN.js, and the output is

nodejs SumToN.js 5 // 127.5

However, executing the code with var myNumber = 5 returns the right answer. What am I missing here?

nihil0
  • 359
  • 2
  • 10

3 Answers3

3

process.argv[2] will be a string. When you use * with a string, it's implicitly converted to a number, but when you use + when one of the operands is a string, it's string concatenation.

So for instance, if you gave 20 on the command line, that calculation becomes

var sumToMyNumber =  "20"*("20"+1)*0.5

which is

var sumToMyNumber =  "20"*("201")*0.5

which is

var sumToMyNumber =  20*(201)*0.5

which is 2010, where you probably wanted 210.

Convert myNumber to a number before doing the calculation:

var myNumber = +process.argv[2];
// ------------^

or

var myNumber = Number(process.argv[2]);
// ------------^^^^^^^---------------^

or

var myNumber = parseFloat(process.argv[2]);
// ------------^^^^^^^^^^----------------^

or

var myNumber = parseInt(process.argv[2]);
// ------------^^^^^^^^----------------^

depending on your needs. This answer has a rundown of how those differ.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

process.argv arguments come in as strings.

So you will get the same result inside the program by setting myNumber like this:

var myNumber = "5";

Instead you need to use parseInt to parse the string into an integer. Or other parse* functions if you want to support floats etc.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

process.argv[2] is being interpreted as a string.

So, '5' * ('5'+1) * 0.5 becomes '5' * '51' * 0.5 becomes 5 * 51 * 0.5 (which is 127.5).

Make sure you convert it to a Number!

var myNumber = Number(process.argv[2])

therobinkim
  • 2,500
  • 14
  • 20