Skip to content
Advertisement

getting NaN when calculating parsed integer difference [closed]

I have a program that counts the number of lines in a text file and it works fine. What I am trying to do is count the number of lines in 2 different files and calculate their difference but I’m getting NaN I parsed them to integers why is it not a number? How can I calculate their difference? Thanks in advance.

filePath = process.argv[2];
fileBuffer = fs.readFileSync('filePath');
to_string = fileBuffer.toString();
split_lines = to_string.split("n");
filePath2 = process.argv[2];
fileBuffer2 = fs.readFileSync('filePath2');
to_string2 = fileBuffer2.toString();
split_lines2 = to_string2.split("n");

//logging NaN
console.log("Calc :" + parseInt(split_lines2.length) - parseInt(split_lines.length))

Advertisement

Answer

Lets take a close look at this line

console.log("Calc :" + parseInt(split_lines2.length) - parseInt(split_lines.length))

Since I don’t have those var’s, lets replace them with some demo numbers:

console.log("Calc :" + 10 - 5);

This will still return NaN because "Calc :10" - 5 fails.

If you enclose the sum in some brackets, there evaluated before adding to the string so it becomes "Calc :" + 5. Since JS will convert the 5 to a string, it producing the expected output:

console.log("Calc :" + (10 - 5));

So you’re console.log should look something like:

console.log("Calc :" + (parseInt(split_lines2.length) - parseInt(split_lines.length)))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement