Why am i getting NaN error? - javascript

I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.
CODE
var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
var fields = lines[i].split(",");
var a = fields[0];
var b = fields[1];
var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
output += outputW + "\n";
}
else {
output += outputL + "\n\n";
}

You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt.
Another remark: your data array is undefined.

you have insert String in parseInt()
a = parseInt("67");
b = parseInt("3");
c = parseInt("2");

Should probably be:
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);

the problem was var lines = data[0].split("/n");
I used the wrong character. It was supposed to be var lines = data[0].split("\n");

The problem is that you are not parsing anything with your parse int.
Take a look here for some docs on parseInt.
Anyway that's how it should look like in your code:
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);
EDIT: following the suggestion of #d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.
Assuming you are parsing integers we can specify 10 as base.

Related

JavaScript program to convert binary to decimal

I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />

Am I correct about .toFixed() and decimals?

I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))

Convert string to expression in JavaScript

I am making a calculator in JavaScript and I want to know how to turn a string into an expression.
var numbers = "5+5+6";
numbers = +numbers;
document.querySelector('.screen').innerHTML = numbers;
Adding + before the variable does not seem to work. I would appreciate it if someone helped.
You can use the eval() function like this:
var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;
Evaluate/Execute JavaScript code/expressions:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:
200
4
27
Without using eval, which is cheating - you could always write a simple calculator app.
First, take advantage of String.split() as follows
var numbers = "5+5+6";
numbers.split("");
// => ["5","+","5","+","6"]
Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.
Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string
var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
.reduce(function(a, b) {
return Number(a) + Number(b)
});
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>

Javascript Calculation not working properly

Hello I am trying to do a simple calculation of three values: a + b * c but getting wrong total. If a is 10 and b is 10 it would be 20 multiplied by c which is 2.4. I should get 48 as total. Currently getting 2424.
function compute() {
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var total = (a + b) * c;
$('#total').val(total);
}
$('#a, #b, #c').change(compute);
Basic maths : multiplication have precedence over addition.
So in your code, a is additionned to the result of b*c .
Use :
var total = (a + b) * c;
a + b * c is being evaluated as a + (b * c)
What you need is (a + b) * c
Precedence: Brackets > Division > Multiplication > Addition > Subtraction
In your question, you stated that you get 1024. Getting 1024 is impossible. You should get 34. (Check your calculation elsewhere)
a + (b * c) = 10 + (10 * 2.4) = 34
If you want to add a to b BEFORE multiplying, you'll need to use parentheses.
That's because the multiplication oprator has higher precedence than addition.
(a + b) * c
try after parsing the values like:
var total = (parseFloat(a) + parseFloat(b)) * parseFloat(c);
$(document).ready(function() {
function compute() {
var a = $('#a').val();
var b = $('#b').val();
var c = $('#c').val();
var total = (parseInt(a,10) + parseInt(b,10)) * parseFloat(c); alert(total);
$('#total').val(total);
}
$('#a, #b, #c').change(compute);
});
Check DEMO
Your variables are strings. Use parseFloat function.
"10" + "10"*"2.4" = "10"+ 24 = "1024"

how to prevent chain when adding javascript variables containing numbers

How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.

Categories