Unable to subtract an integer value in javaScript Protractor - javascript

I need to compare an array length with the text displaying numbers in the UI. I stored the array length in 'X' variable, whereas the text in 'len' variable.
I need to reduce the X by 3 and compare with the string 'len'.
EG: Len value is '+31' which is string. and X value is 34.
Please help me out to compare both the values. I tried converting both to string or int. Nothing helps me out.
var len=createMenu.numPrivSelected.getText();
var x=createMenu.returnLength(createMenu.selectedpriv);
console.log(len+","+x-3);
expect(len).toEqual(x);
returnLength() is a method which returns the length of the element.
numPrivSelected is an element which returns text as '+31'.
Output is:
NaN
Expected '+31' to equal 34.

Well first, your console.log is return NaN because it's trying to do arithmetic on the string.
console.log(len+","+x-3);
It would go like this:
len+","+x-3
"+31,"+x-3
"+31,34"-3
And obviously "string minus integer" won't work, so that's why it resulting in NaN (Not a Number).
Secondly, if you want to compare two numbers you need to make sure they're both numbers. The + sign in len makes it a string, and it can't be converted to a number directly. First you'll have to remove the plus sign. Here's your code, adjusted to fix the obvious errors that I can see:
var len=createMenu.numPrivSelected.getText();
var x=createMenu.returnLength(createMenu.selectedpriv);
len = len.replace("+","");
x -= 3;
console.log(len+","+x);
expect(len).toEqual(x);

I tried as below and it worked,
var len;
var x;
createMenu.returnLength(createMenu.selectedpriv).then(function(num){
len=num-3;
console.log(len);
});
createMenu.numPrivSelected.getText().then(function(text){
x=text.replace("+","");
console.log(x);
});
expect(len).toEqual(x);

Below code should work,
var len = createMenu.returnLength(createMenu.selectedpriv).then(function(num){
return num-3;
});
var x = createMenu.numPrivSelected.getText().then(function(text){
return parseInt(text.replace("+",""));
});
expect(len).toEqual(x);

Related

Adding two variables in Javascript [duplicate]

This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 3 years ago.
I want to take a number input (id="number") and save it as "x". Then make another variable, "y", that is 5% of "x". And then I want to add them together and save the result in a variable called "result".
Let's say that x = 100. Then y = 5. If I would just alert "y" it would alert the number 5 which is correct but the problem is that when I try to alert "result" (x+y) it alerts 1005 (it doesn't add the numbers just write them next to each other).
let x = document.getElementById("number");
let y = x*0.05;
var result = x+y;
alert(result);
Fist get value and so convert it to number:
Change :
var x = document.getElementById("number")
to :
var x = parseInt( document.getElementById("number").value )
Note : You must convert the input to a number even if type property be equal with number.
function fun() {
var x = document.getElementById('number').value;
console.log( typeof x)
var y = parseInt(document.getElementById('number').value);
console.log( typeof y)
}
<input type="number" id="number">
<button onclick="fun()">Go..</button>
you need a value for doing some calculation. so,
var x = document.getElementById("number").value;
"+" operator will concatenate if string value exist. var x is string value but automatic type casting will occur when var y=x*0.05. so you must cleary declaire "x is number" via parseInt().
var x = parseInt(document.getElementById("number").value);
Now "+" operator will work as you expected.
What's going on is x+y is performing string concatenation, not integer addition--which is what you want.
// String concatenation
console.log("100" + "5"); // outputs "1005"
// Integer Addition
console.log(100 + 5); // outputs "105"
That's the problem, but what's the solution?
The solution is to force integer addition with something like parseInt() (as Ehsan mentioned)
var x = parseInt( document.getElementById("number").value );
Worth noting is the fact that Ehsan uses document.getElementById("number").value, instead of document.getElementById("number")
This forces x to be an int, which will allow x+y to perform integer addition.
P.S. I should also note part of the reason for your problem is related to the fact that document.getElementById("number").value is a string, forcing a type conversion to take place
Addition ‘+’ concatenates strings
Almost all mathematical operations convert values to numbers. A notable exception is addition +. If one of the added values is a string, the other one is also converted to a string.
Then, it concatenates (joins) them:
alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)
This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.
Meaning that one of the operands (again, document.getElementById("number").value is a string) in an addition operation being a string forces both to become strings and get concatenated.

Display "$xx.90" instead of "$xx.9" in Javascript

When I use p=10000 ,r=15 and n=60 in the below ...
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));
x = 237.9 instead of 237.90.
If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.
But why is it displaying 237.9 instead of 237.90?
When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:
var number = 237.9;
number.toFixed(2); // '237.90'
However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:
parseFloat(number.toFixed(2)); // 237.9
To avoid this, simply don't convert your string back into a float, but use it as a string.
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
p=10000,r=15, n=60;
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);
console.log(x)
Add toFixed after all operations. You need string, basically...

Javascript parseInt not working on a string, trying to get an integer from an HTML value

I am making a basic game, and I have a tile system that I'm using. Each tile has an ID of "tileX", where X is a number (ex. tile1). I have a function as follows:
window.onclick = function() {
var x = event.clientX, y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y).id;
document.getElementById("tileTell").value = elementMouseIsOver;
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
elementMouseIsOver = parseInt(elementMouseIsOver);
console.log(elementMouseIsOver);
console.log(typeof(elementMouseIsOver));
}
Line 4 of code there fills in an input field so I can visually see which tile I've clicked (I'm using this to make sure things are working properly and so I can find the tiles I need). That works fine. On line 5 when I do a console.log, it gives me the proper ID, and verifies that it is a string.
After that I want to reset the elementMouseIsOver variable to be an integer, so if the ID was tile1 I would expect the new result to be 1. But when I look at it in the console, I get NaN. And then when I check the type of it immediately after that, I get number.
The parseInt does not seem to be working properly, what am I doing wrong? I need to use the ID names of each tile for mathematical operations so this is vital to my game. I know it's probably a really dumb mistake but I am completely at a loss...
If you want parseInt() to work on strings in the way you're using it, it has to start with a digit; in your case, it starts with alphabetical characters, and so (with an implicit radix of 10) it will rightfully return NaN.
You could get the number out by using a generic method:
var num = +(elementMouseIsOver.match(/\d+/) || [])[0];
It matches the first group of digits it can find and then uses the unary plus operator to cast it into an actual number value. If the string doesn't contain any digits, it will yield NaN.
In your particular case, you could also apply parseInt() on the part that immediately follows "tile":
var num = +elementMouseIsOver.substr(4);
NaN is correct.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
Nothing parsed successfully.
EDIT
You could accomplish what you want by removing the non-numeric characters from the string, assuming you'll always have a string+integer as the ID. Try this:
parseInt(elementMouseIsOver.replace(/[^\d]/,""))
You need to remove the "tile" string first, so it can properly parse the value:
elementMouseIsOver = parseInt(elementMouseIsOver.substring("tile".length));
.substring("tile".length) returns a substring starting with the character after "tile" (position 4 in the string, count starts at 0), resulting in only the number of the ID (as a string).
fiddle: http://jsfiddle.net/rk96uygd/
The typeof of a NaN is number.
Use isNaN() to test if a value is NaN or Not a Number
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
You could also use the Number() cast instead of parseInt().
you trying to parseInt on a element ID that is non-numeric, when parse fail it will return NaN (*or not a number*)
elementMouseIsOver = parseInt(elementMouseIsOver);
moreover, your elementMouseIsOver is an ID of control, I don't think .value can get the value of control
elementMouseIsOver = document.elementFromPoint(x, y).id;

Javascript parseInt on large negative number gives NaN

When I do this:
var x = parseInt("–2147483648");
console.log(x);
I get the value as:
NaN
Why does this happen?
I want to test if a number is in the range of C (int), so I am doing the above, but it does not work. Also, I want to do this for C (long), is there a way to this?
For example:
If I do:
var x = parseInt("-9223372036854775808");
console.log(x);
Now, I know that (-+)2^53 is the limit of numbers in Javascript. Is there some other way to test if the given value in a form is actually in the range of long or int?
It should work fine, the problem is that you're using the wrong character, an ndash – vs a hyphen -:
var x = parseInt("-2147483648");
console.log(x);
If you copy/paste that you'll see that it works now.

Subtraction in JavaScript only returns two digits of the thousands

I have two variables holding integer values:
x = 36,000;
y = 18,045.40;
this is how i subtract:
z = parseInt(x) - parseInt(y);
the result is 15.
If i remove the parseInt the result is 'Nan'.
How do I go about subtracting x with y without rounding off or removing thousands?
many thanks.
Don't put commas in your numbers.
The code you have posted won't even run. I would recommend pulling the ,s out of your numbers and using parseFloat instead. This appears to give the result you want. Demo here:
http://jsfiddle.net/yVWA9/
code:
var x = 36000;
var y = 18045.40;
alert(parseFloat(x) - parseFloat(y));
There is no separator for thousands in Javascript. Your variables are either holding strings and not integer values or you are getting syntax error.
If you have strings and they cannot be changed (like received from service, etc.) then try this:
x = "36,000";
y = "18,045.40";
// remove commas and convert to numbers
function norm(num) { return +num.replace(',', ''); }
console.log(norm(x) - norm(y));

Categories

Resources