Numbers are concatenated instead of added together - javascript

I need the two numbers to be added but somehow they are concatenated. Where am I doing it wrong?
var a;
var b;
var parsedInta;
var parsedIntb;
a=window.prompt("enter your first number");
b=window.prompt("enter your second number");
parsedInta=parseInt(a);
parsedIntb=parseInt(b);
alert("The Sum is" + parsedInta+parsedIntb);
It concatenates the result rather than addition.

You have to introduce parentheses to force the numeric addition to happen before the alert string is built:
alert("The Sum is " + (parsedInta + parsedIntb));
Without the parentheses, the + operator is naturally left-associative, so the first "addition" carried out is the string concatenation between "The Sum is" and the first value (which is treated as a string).
edit — note that the + operator prefers string concatenation over numeric addition. If either operand of + is a string, then the other operand is converted to a string and the two are concatenated.

This is beacuse the + operator is used also to do string concatenation. Since in your "The Sum is" + parsedInta+parsedIntb you are working with a string the language thinks you want to use parseinta and parseintb as strings.
You can solve by simply doing the sum before the string creation:
var sum = parseInta + parseIntb;
alert("The Sum is" + sum);
Or also by using parseInt directly in the sum line:
var sum = parseInt(a) + parseInt(b);
alert("The Sum is" + sum);

The probleme is that you are doing implicit type casting using "+" operator which will convert the number to string so your code will be like :
alert("the sum is "+number1+number2); //The number 1 will be converted to a string
,the same for the second number
So if i enter 10 in the first prompt and 10 in the second prompt the alert will show : the sum is 1010 because the first 10 is converted to a string and the second 10 will be converted to a string
But if i use parenthese like :
alert("the sum is "+(number1+number2));
Here the two number will be added and it will be coverted to a string after the addition.
P.S : don't use window object because it's a global object so you can ignore it
And sorry for my bad english i hope that you will understand

This is JavaScript. Don't expect the language to make sense.
This is because the + operator is overloaded for strings. If either of its operands is a string, + will turn the other operand into a string and concatenate them.
Since this awful operator is also left-associative, you will get
("The Sum is" + parseInta) + parsedIntb
which is a string plus a number (which is a string) plus a number, which is also a string.
Parenthesize the rightmost addition instead:
alert("The Sum is" + (parsedInta + parsedIntb));
And maybe consider starting to learn programming with a sane language.

Related

Javascript adding numbers as if they were a string [duplicate]

This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
I have been playing around with cookies for the first time, and I have saving part of it completed. The data I'm saving are numbers and the most important part of these nubers is that I can add, subtract and so on with these. However when I try to add a number to one of my saved parametres it adds them as if they were text.
Example:
I have a cookie called value, and when I want this value I use a script I found by Jeffery To that looks like this:
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
After I have collected this cookie I want to add one to it. Lets say that value equals nine, when it should look like this: value + 1 = 10. Simple math. However it gives me this 91. Why does it do this? I know that it is because it thinks the numbers are a string of text, but how can I get this to behave like numbers?
Solution
After reading the comments I learned that i needed to put my value inside a parseInt(). So i simply modified the funtion to say:
function readCookie(name) {
return parseInt((name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]);
}
The + operator in JavaScript can mean mathematical addition or string concatenation. The one you get is based on the implicit type of the operands. If one of the operands is a string, the other will be converted to a string and you'll get concatenation.
The trick is to do the math on the numbers first (you can surround the math portion with parenthesis or do the math in a separate statement) and then inject the result into your string.
To force a string containing a number character into a number, you can use parseInt() and parseFloat():
var result = parseInt(value, 10) + 1;
Note that with parseInt(), you should supply the optional second argument, which specifies the radix for the operation. If the first argument happens to refer to a string that contains a hex value, the result will be based on hex, not base 10. That's why 10 is used in my example.
Also note that both parseInt() and parseFloat() stop after finding the first non-valid characters that can't be treated as numbers. So, in a string like this: "Scott7Marcy9", you would get NaN.
Cookies are saved as string values as you guessed. To get your desired effect, you're going to need to parse your value. If you are absolutely sure it will be an integer, use:
parseInt(value) + 1

What does "= +" do in JavaScript?

Was reading through Douglas Crockford's code here and saw a line
var value = +node.getValue();
but I don't see anything at http://www.w3schools.com/js/js_operators.asp which corresponds to an = + or a way that + can be used as a unary operator. So what does this mean?
The - and + operators are both unary in JS and, before forcing the value's sign, must convert the value to a number.
Obviously - will convert to a number and invert the sign, but + only does the first part. Running +"100" will return the number 100.
This behavior is explicitly stated in the spec at 11.4.6, where the unary + operator is defined:
The unary + operator converts its operand to Number type.
It's just a quick way to make sure the variable is an INT, (vs. a STR or BOOL, e.g.).
Just to add on to what's been said do the following:
var a = +'4';
var b = '4';
console.log(typeof(a));//Number
console.log(typeof(b));//String

Type of message in javascript window alert

I am trying to alert the following,
1. alert(1+1+1+1+1);
//output: 5
2. alert('1'+1+1+1+1);
//output: 11111
3. alert(1+1+1+1+'1');
//output: 41
4. alert(1+1+'1'+1+1);
//output: 2111
Does anyone can explain about the type of message in alert ?
Thank you in Advance.
Alright so in javasciprt, number + number + number = number (Your case 1)
Whereas, a number after string concatenates with the String, and results in a string as output '1'+1 = '11' + 1 = '111' and so on. (Your case 2)
In the third case, the string just comes at the end of the number which get's casted to string and result will simply be number followed by string in string form.. 2+'432' = '2432'.
Last case is the mix of all the above 1+1 = 2 + '1' = '21'+1 = '211'+1 = '2111'.
Javascript is a weakly typed language with operator overloading. That is why you are getting those 'strange' behaviours.
Wow, operator overloading. huh?
The + in javascript has multiple functions. One being: adding up numbers and another one is concatenating strings together. this is called operator overloading. compared to PHP, adding up numbers is + but concatenating strings is .
The big problem with operator overloading is. What if we have String + Number. Or Number + String ?
Different rules apply:
1+1+1+1+1
This is easy, adding up 5 numbers.
'1'+1+1+1+1
This is harder one. What he sees is a String, so he concatenates it with the next part (the 2nd 1). Then he continues. String(11) + 1, gives String(111) and so on.
The 3rd example is fun. he starts adding up all the numbers, untill he reaches the last + sign. And it no has Number(4) + String(1). So he converts the Number to a string and Concatenates them together.
Same goes for the last example. If one of the two is a String, the + sign is interpreted as a Contatenation.
I was reading w3school's Automatic type conversion and I think this is relevant from your question.
It says:
When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.
It says that the result is not always what you expect:
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 1 // returns "51" because 1 is converted to "1"
"5" - 1 // returns 4 because "5" is converted to 5

Adding +1 to jQuery value of a readonly text input field

I am using a function where I have a readonly text input, and when I execute the function I want the number value + 1. So let's say I have 60, when I execute the function, the number returned should be 61.
But instead it's coming out 601, which is just adding the number 1 to the string. Any clue as to what is going on? Subtraction, multiplication and division all work fine. Here is a snippet
var num= $("#originalnum").val() + 1;
$("#originalnum").val(num);
And yes i've tried a few different variations, am I missing something?
A simple unary + is sufficient to turn a string into a number in this case:
var num = +$("#originalnum").val() + 1;
$("#originalnum").val(num);
The problem is that .val() returns the value of the element as a string, and when you use the + operator on a string it does string concatenation. You need to convert the value to a number first:
var num = +$("#originalnum").val() + 1; // unary plus operator
// OR
var num = Number($("#originalnum").val()) + 1; // Number()
// OR
var num= parseFloat($("#originalnum").val()) + 1; // parseFloat()
// OR
var num= parseInt($("#originalnum").val(),10) + 1; // parseInt()
Note that if you use parseInt() you must include the radix (10) as the second parameter or it will (depending on the browser) treat strings with a leading zero as octal and strings with a leading "0x" as hexadecimal. Note also that parseInt() ignores any non-numeric characters at the end of the string, including a full-stop that the user might have intended as a decimal point, so parseInt("123.45aasdf",10) returns 123. Similarly parseFloat() ignores non-numeric characters at the end of the string.
Also if it's a user-entered value you should double-check that it actually is a number and perhaps provide an error message if it isn't.
When you use the *, / or - operators JS tries to convert the string to a number automatically, so that's why those operators "work" (assuming the string can be converted).
You should use the parseInt function and make sure the value is number(use isNaN function):
var val = $("#originalnum").val();
var num = 0;
if ( !isNaN(val) )
num= parseInt(val) + 1;
Use parseInt():
var num= parseInt($("#originalnum").val(),10) + 1;
So your number is treated as an integer instead of a string (as .val() treats the result as string by default)
If you don't like the above code spelling, you can try it this way too.
$("#originalnum").val(function() {
$(this).val(parseInt($(this).val()) + 1)
});

Javascript + operator vs - operator

I am puzzled by this snippet:
var n1 = 5-"4";
var n2 = 5+"4";
alert(n1);
alert(n2);
​I understand that n1 is 1. That is because a minus operator would convert the string "4" into number and subtract it from 5.
But why do we get 54 in case of + operator?
Can someone explain this difference between + and = operators to me?
By type conversion any + expression, that contains a strings, will result in a string. Thus all operands (in your case 5) will be converted to a string, before executing the concatenation.
- on the other hand is just an arithmetic operand, thus "4" is converted to an integer and the calculation is performed as you expect.
It's because in n2, + is being treated as concatenation, not addition. So 5 is converted to the string "5" and "4" is concatenated, giving "54".
When there's a string in either side of +, the + will be considered as a string concatenating operator, the other side will be converted to string and then do the concatenating.
And be careful of something like 1+2+'3', the result is '33' rather than '123'.
- operator has only one meaning - numbers subtraction (or negation and in that case, also conversion to number). In case of + operator, however, there are two: number addition and strings concatenation. When one of the operands of + operator is a string it does string concatenation instead of numbers addition.
The entire process is a bit more complicated than that though and involves an algorithm that you can learn a bit more here, for example.
The + operator is also a string operator. Quite every basic type variable in javascript can be interpreted also in its string representation. You are just attaching 5 to 4 getting 54.
The - operator is not a string operator so the compiler tries to interpret "4" as a number, thus getting 1
Javascript takes 5 as a number and "4" as string.
The javascript + operator use to concat two things.
If you want to addition please use parseInt.
var n1 = 5-"4";
var n2 = parseInt(5)+parseInt("4");
alert(n1);
alert(n2);

Categories