Adding two variables in Javascript [duplicate] - javascript

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.

Related

Why am I getting a number and not a concatenated string?

I have this code
var n = parseInt(prompt("Give me a number"));
var sum = 0;
for (let i=0; i < n.toString().length; i++){
let expon = n.toString()[i] ** n.toString().length;
sum += expon;
}
My doubt is the following: If my n is 371, n.toString()[0] is '3' (A STRING!!), why is it then that when I do ** n.toString().length (which is 3). I get 27 ?!!?
Also, it is clear to me that if x = '3' and I do x + x I get '33' and not 6. Can this happen to the addition only? why?
'3' ** 3 is 27 because ** converts both its arguments to numbers if possible. It has no function other than numeric exponentiation.
'3' + 3 is '33' because + has multiple possible functions (addition and string concatenation), and if at least one of the arguments is a string, string concatenation is used instead of addition. In another universe, it may well attempt to do numeric addition first and end up at 6, but the language designers of our universe chose to do it this way round.
Check this: https://medium.com/swlh/strings-and-basic-mathematical-operators-in-javascript-e9de3d483dae
In simple words - in JavaScript, when trying to add String type to non-String type, adding operator automatically casts added elementsto both be set of characters, because '+' can be understood as adding OR as concatenating. Although, every different arithmetic operations (substracting, dividing, multiplying, powering, etc.) performed on String and non-String type will force the first one to be casted to the Number form. If not possible, we will receive NaN result.

Unable to subtract an integer value in javaScript Protractor

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

parseInt fixing the value

Here I have a value with commas.
Ex:-var abc = "10,10.12";
If I use var x = parseInt(abc);
it is returning 10
Expected output is 10,10.12
as I have used ng-value="UpdatedPropuesta.VALOR_CUOTA | number:2" in JSP.
If you want an array of numbers out of the string then try this,
const input = "10,10.12";
var output = input.split(",");
output = output.map(i => Number(i));
console.log(output);
10,10.12
That is not the number 1010.12, it is the number 10, a comma operator, and the number 10.12.
Commas are not part of the JavaScript literal syntax.
However, in your case you're passing two arguments to parseInt, the first should be a string to convert (but JS will convert it to a strign) and the second is the radix – the number base – which should be an integer.
So JS's type conversion will lead to:
var x = parseInt('10', 10);
Which is of course 10.
After question update
var x = parseInt("10,10.12");
As comma are not part of JS numeric literals, the parse will stop at the comma because it is not a character that can appear in a number.
So the answer is still 10.

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

why do I get 24 when adding 2 + 4 in javascript

I am trying this:
function add_things() {
var first = '2';
var second = '4';
alert(first + second);
}
But it gives me 24 instead of 6, what am I doing wrong?
You're concatenating two strings with the + operator. Try either:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
or
function add_things() {
var first = '2';
var second = '4';
alert(parseInt(first, 10) + parseInt(second, 10));
}
or
function add_things() {
var first = '2';
var second = '4';
alert(Number(first) + Number(second));
}
Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).
Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.
Try this:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
Note that I've removed the single quotes; first and second are now integers. In your original, they are strings (text).
That is one of the "Bad Parts" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.
JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.
Basically there are three primitive data types:
boolean
number
string
null and undefined are two special cases, everything else are just variations of the object type.
JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).
In your example were trying to add two objects of type string, so a concatenation occur.
You can "cast" or type convert the variables to number in many ways to avoid this problem:
var a = "2";
var b = "4";
// a and b are strings!
var sum = Number(a) + Number(b); // Number constructor.
sum = +a + +b; // Unary plus.
sum = parseInt(a, 10) + parseInt(b, 10); // parseInt.
sum = parseFloat(a) + parseFloat(b); // parseFloat.
This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).
The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation.
The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.
The single quotes cause the values to be treated as characters instead of numbers. '2' + '4' = '24' in the same way that 'snarf' + 'blam' = 'snarfblam'.
You could also force the interpreter to perform arithmetic when dealing with numbers in string forms by multiplying the string by 1 (since multiplication can't be done on a string, it'll convert to a number if it can):
// fun with Javascript...
alert(first * 1 + second * 1);
But it's probably best to go with CMS's suggestion of using Number() to force the conversion, since someone will probably come along later and optimize the expression by removing the 'apparently unnecessary' multiply-by-one operations.

Categories

Resources