getting NaN when calculating parsed integer difference [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
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))

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)))

Because you do math together with "Calc :":
"Calc :" plus split_lines2.length, minus split_lines.length - no concatenation here.
Wrap calculations inside (), so your + becomes concatenation instead of addition
/* 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"); */
var split_lines2 = [1, 2];
var split_lines = [1]
//logging NaN
console.log("Calc :" + (parseInt(split_lines2.length) - parseInt(split_lines.length)))

Related

Need help to understand Vue.js function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an assignment to make calculator using vue.js.
Much of it works, I'm confused about how to implement the '=' function.
I found this piece of code in an article that does something similar but I don't understand what it does. Can someone explain it?
https://scotch.io/tutorials/build-a-scientific-calculator-with-vuejs
I found this Piece of code:
if ((app.current).indexOf("^") > -1) {
var base = (app.current).slice(0, (app.current).indexOf("^"));
var exponent = (app.current).slice((app.current).indexOf("^") + 1);
app.current = eval("Math.pow(" + base + "," + exponent + ")");
} else {
app.current =app.current
}
Can someone please explain what the above function does, line-by-line?
// checks if app.current have '^' by getting the index
// if the method indexOf doesn't find anything it return -1
if (app.current.indexOf('^') > -1) {
// gets the first element till the index where it found '^'
var base = app.current.slice(0, app.current.indexOf('^'));
// gets the number after the 'ˆ'
var exponent = app.current.slice(app.current.indexOf('^') + 1);
// eval is evil
// it gets the string and transfoms into valid code
// wich means to do the operation
app.current = eval('Math.pow(' + base + ',' + exponent + ')');
} else {
// if it doesn't find the index it keeps the same value
app.current = app.current;
}
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

How to add number like 1+1+1=3 not "1"+"1"+"1" = 111 in javascript [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
Closed 5 years ago.
Here is my code:
var health = prompt("Type in health");
var attack = prompt("Type in attack");
var defense = prompt ("Type in defense");
function calculatestats(health,attack,defense){
return health/4 + attack + defense
}
alert (calculatestats(health,attack,defense));
I want to make it output "3" when I type in 4, 1, and 1. The javascript is adding the characters, "1", "1", and "1". I want to add it Mathematically, and make it output 3, not 111.
Thank you.
The prompt() returns a string. You have to do explicit type conversion using + or parseInt:
function calculatestats(health,attack,defense){
return +health/4 + +attack + +defense;
}
Better way:
function calculatestats(health,attack,defense){
return parseInt(health)/4 + parseInt(attack) + parseInt(defense);
}

currency filter for large amount in angular [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I am building an angular app involving large amounts. I'd like to shorten the way their are displayed so I built a quick and dirty filter replacing '1000000000' by '$1.0Bn' for example but it is really dirty and it just truncate the numbers instead of rounding them up.
Here it is:
.filter('largeAmountCurrency', function() {
return function(input) {
if (!input) return;
var oneBillion = 1000000000,
oneMillion = 1000000;
if (input > oneBillion)
return '$' + parseInt(input / oneBillion) + '.' +
String(parseInt(input - parseInt(input/oneBillion))).substring(1,3) + 'Bn';
if (input > oneMillion)
return '$' + parseInt(input / oneMillion) + '.' +
String(parseInt(input - parseInt(input/oneMillion))).substring(1,3) + 'M';
return input;
}
});
Is their any prebuilt filter in angular which does this job? Or how can I shorten it dramatically?
You can compute a few things using Mathematical logarithm log!. This will help you knowing the number of digits your input has.
Example (log is base 10 logarithm, ln is napierian logarithm) :
log(12345678910) = ln(12345678910)/ln(10) = 10
Here, 10 is the number of digits after the first '1'.
Based on this information you can compute a simplified value, and then round it with toFixed! (This works with IE5.5+, Javascript 1.5, I assumed you get it when you use AngularJS)
A complete example below :
var number = 12345678910;
var digits = 2;
var suffix = ["", "K.", "M.", "B."];
var nbDigits = Math.round(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;
var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);
var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];

How to extract a number from a two line string in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I would like to extract the number "40" from following two lines:
Total Boys:4 (40 min)
Main Students:0 (0 min)
How can I do that using javascript? Thank in advance!
Or without a regex
str.split('min').shift().split('(').pop().trim();
FIDDLE
Simply use a regular expression:
var str = 'Total Boys:4 (40 min)\nMain Students: 0 (0 min)';
var number = str.match(/\((\d+)/)[1]; // 40
Here's a simple regex to pull that value out:
var str = 'Total Boys:4 (40 min)\nMain Students:0 (0 min)';
var regexp = /.*\((\d+) min\)\n.*/;
var matches = regexp.exec(str);
alert('match: ' + matches[1]);
Another way of doing it would be simply str.match(/\d+/g)[1] using regex.
DEMO
suppose you have your string inside str andyou want to store the number inside n
another approach is this:
var index1,
index2,
index3,
n;
index1 = str.indexOf('Total Boys:', 0);
index2 = str.indexOf('(', index1) + 1;
index3 = str.indexOf(' ', index2);
n = str.substring(index2, index3);
note that this approach will get only the min value of "Total Boys", not "Main Students".
It will work even if you have another similar line before "Total Boys"

Why does this function return NaN? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
function getNucleobaseCount (strand) {
/*
Returns occurences of nucleobases A and C respectively
*/
var countA = (strand.split("A").lenght - 1);
var countC = (strand.split("C").lenght - 1);
return countA + " " + countC;
}
But
> console.log(getNucleobaseCount("AAGCATT"))
Nan Nan
Instead of the expected 3 1
Why?
The value of the lenght property will be undefined.
undefined - 1 is NaN
You misspelt length.
Misspelling of length? I would think that it would show a compilation error though.
you have
misspelled 'length' :-)
function getNucleobaseCount (strand) {
/*
Returns occurences of nucleobases A and C respectively
*/
var countA = (strand.split("A").length - 1);
var countC = (strand.split("C").length - 1);
return countA + " " + countC;
}

Categories

Resources