Adding two numbers in JavaScript incorrectly [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
Global.alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront));
The code above outputs something like:
base: 15000, upfront: 36, both: 1500036
Why is it joining the two numbers instead of adding them up?
I eventually want to set the value of another field to this amount using this:
mainPanel.feesPanel.initialLoanAmount.setValue(Ext.util.Format.number((base + upfront), '$0,000.00'));
And when I try that, it turns the number into the millions instead of 15,036.00. Why?

Simple example:
1 +1 == 2
"1"+1 == "11"
"1"*1 + 1 == 2
Ways to turn a string into a number:
parseInt(str)
parseInt(str,10)
parseFloat(str)
+str
str*1
str-0
str<<0
Number(str)
And here are some of the consequences:
(source: phrogz.net)
Number(str) has the same behavior as str*1, but requires a function call.
I personally use *1 as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt() when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.
You can test the performance of these in your browser at my example page.

This might happen because they are strings. Try parsing them:
Global.alert(
"base: " + base + ", upfront: " + upfront + ", both: " +
(parseInt(base) + parseInt(upfront))
);
If those numbers are decimal you will need the parseFloat method instead.

Try
Global.alert(
"base: " + base + ", upfront: " + upfront + ", both: " +
(parseInt(base,10) + parseInt(upfront,10))
);
The 10 specifies base 10, otherwise the chance of the value being parsed as octal exists.

http://jsperf.com/number-vs-parseint-vs-plus/3
That might also be of interest to you.
It is just a performance comparison of the methods already mentioned here.

I don't know why the brackets aren't helping you out.
If I try
var base = 500;
var upfront = 100;
alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront))
I do get 600 as the answer, so it could be there is something going on in the Global.alert function?
One of the mistakes of the language design is that + is both an addition operator and a concatenation operator. Coupled with the fact that it is loosely typed and will cast implicitly means that it can give you some nasty surprises unless you take steps to ensure that you really are adding numbers and not concatenating strings. In this case, it is treating your base + upfront as strings and therefore concatenating.
Anyway, the way around it could be to have (base - upfront*-1) instead.

It's handling it as a string. You need to do your math before the string. Example:
base + upfront + ' string'
would return "15036 string".
string + base + upfront
would return string 1500036 as you are seeing now.
Or use parseInt().

Related

Why (4 + 5 + "6") is 96 but ("4" + 5 + 6) is 456 on Javascript?

console.log(4 + 5 + "6");
console.log("4" + 5 + 6);
I think it is something related to element type(string, number)
But I can not find the proper document explaining this concept.
Whenever a number and a string are added together, the number turns into a string. Because of this adding 4 and 5 will equal 9, because they are both numbers, but adding 4.toString() and 5.toString() will result in 45, because the + operator isn't actually adding, it is joining two strings.
When you do console.log(4 + 5 + "6");, the numbers 4 and 5 are being mathematically added first, which is 9, and then 9 gets converted into a string and 6 gets added on to it.
When you do console.log("4" + 5 + 6);, the number 5 gets converted into a string and joined to the string "4". Same thing happens with the 6. This results in the string 456.
Like #Pointy said, this can be changed by changing the order of operations. Parenthesis will be calculated first. For example, console.log("4" + (5 + 6)); will result in 411, because the 5 and 6 will be mathematically added first, then converted into a string and added on to 4.
Great question, and I didn't think about that until today :)
Most operators in JavaScript expressions are evaluated left to right, so 4 + 5 + "6" is interpreted as (4 + 5) + "6". Thus the numeric addition is performed first, followed by the string concatenation. In the second example, the left-most operand is a string, so both + operations are string concatenation.

Why '+' act like a parse in javascript when converting from string to float or integer and how it differs regarding on performance?

parseFloat("10.1") + parseFloat("32.3")
vs
+ "10.1" + + "32.3"
both statement will produce the same result 42.4
using this statement:
+ "10.1" + + "32.3"
Why does + act like a parse and how each statement affects the performance in the program?
JavaScript uses implicit conversions. The unary + only accepts numbers, so, when you give it a string, it converts it into a number. JavaScript does this by parsing the string as a number. Since JavaScript doesn't have an integer type, it is always parsed as a floating point number.
To answer the performance question: jsperf.
From my tests, the unary operator + is 8 times faster than parseFloat.
I'd guess this has to do with the expense of function calls in JS, etc.

java script: 3 + 0 = 30 [duplicate]

This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
JavaScript:
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
Console in browser returns: adding3+0=30
Im debugging a loop that interpolates two numbers. It works fine until addThis (the amount that needs to be added to the original number) is exactly 3 and p1 (the original value) is 0.
Every time the difference(addThis) has no decimals a wrong calculation happens.
So same problem at:
adding6+0=60 ...or at..
adding9+0=90
...all cases in between work fine (e.g. console returns: adding3.5999999999999996+0=3.59999999999999960)
Dose it 'forget' the point?
Dose it treat those values as strings?
I can't share the whole code but the problem has to be in this simple calculation right?
Thanks a lot for your thoughts and knowledge! ;)
3+0=30. It seems like it must be the string (at least anyone variable is string). You can re-visit the lines where those variable values are initialized/changed. Else you can use like the below:
addThis=Number(addThis); p1=Number(p1);
console.log('adding' + addThis + '+' + p1 +'=' + (addThis + p1));
If you want to convert the strings to integers you can use the parseInt function:
addThis = '3'
p1 = '0'
console.log('adding' + addThis + '+' + p1 +'=' + (parseInt(addThis) + parseInt(p1)))

How can I concatenate arithmetic and strings?

So javascript uses the plus operator to concatenate strings with strings and/or integers like so:
<script>document.write("One plus Two equals " + 3);</script>
<script>document.write("One plus Two equals " + "three");</script>
At least I think it does :/ --Because of this, things get confusing if I wanted to concatenate integers and/or strings with arithmetic. I shall try here anyway. don't laugh :(
<script>document.write("One plus Two equals " + 1+2);</script>?
I wonder, could the solution as easy as adding moar parentheses?!
<script>document.write("One plus Two equals " + (1+2));</script>
Am I way off base here?

Javascript (+) sign concatenates instead of giving sum of variables

Why when I use this: (assuming i = 1)
divID = "question-" + i+1;
I get question-11 and not question-2?
Use this instead:
var divID = "question-" + (i+1)
It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.
Since the + operator will be handled left-to-right the decisions in your code look like this:
"question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
"question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".
With "question-" + (i+1) it's different:
since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
i is numeric, 1 is numeric, so we'll do addition, resulting in 2
"question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
You may also use this
divID = "question-" + (i*1+1);
to be sure that i is converted to integer.
Use only:
divID = "question-" + parseInt(i) + 1;
When "n" comes from html input field or is declared as string, you need to use explicit conversion.
var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);
If "n" is integer, don't need conversion.
n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;
Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:
i = i + 1;
divID = "question-" + i;
Or you need to specify the number addition like this:
divID = "question-" + Number(i+1);
EDIT
I should have added this long ago, but based on the comments, this works as well:
divID = "question-" + (i+1);
divID = "question-" + parseInt(i+1,10);
check it here, it's a JSFiddle
Another alternative could be using:
divID = "question-" + (i - -1);
Subtracting a negative is the same as adding, and a minus cannot be used for concatenation
Edit: Forgot that brackets are still necessary since code is read from left to right.
Add brackets
divID = "question-" + (i+1);
using braces surrounding the numbers will treat as addition instead of concat.
divID = "question-" + (i+1)
The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.
In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".
You just simply need to give the interpreter a hint as to what order of prec endence you want.
divID = "question-" + (i+1);
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
var divID = "question-" + (parseInt(i)+1);
Use this + operator behave as concat that's why it showing 11.
Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
In case of integers, var num = 0;
In case of strings, var str = "";
Even if your i variable is integer, + operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.
- (minus operator) cannot be misunderstood and you will not get unexpected result/s.
One place the parentheses suggestion fails is if say both numbers are HTML input variables.
Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.
HTML inputs were intended numerical values for variables a and b, so say the inputs were 2 and 3.
Following gave string concatenation outputs: a+b displayed 23; +a+b displayed 23; (a)+(b) displayed 23;
From suggestions above we tried successfully : Number(a)+Number(b) displayed 5; parseInt(a) + parseInt(b) displayed 5.
Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.
Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.
Use parseInt(i) than the value of "i" will be casted to Integer.
Than the "+" operator will work like addition.
In your case do this :-
divID = "question-" + parseInt(i)+1;

Categories

Resources