views:

103

answers:

5
Global.alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront));

This code above outputs this:

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 now it turns the number into the millions instead of 15,036.00. I have no idea why. Any ideas?

+6  A: 

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.

Darin Dimitrov
A: 

its 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()

Mark
He's using parenthesis, so the addition will execute before trying to merge with the other string (i.e. you don't have to do your math "before" the string if you use parenthesis). But, parseInt would work - the **+** operator is treating at least one of his operands as strings.
palswim
+2  A: 

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.

davidj
Just a minor nit - while you are right about always specifying the base being a good idea, the default base is indeed 10 and not octal. It assumes octal for strings that start from zero (such as `"0120"`).
Chetan Sastry
So changing from "otherwise it is octal" to "otherwise the chance of the value being parsed as octal exists" would be a good edit? It's all about best practices, right?
davidj
+1  A: 

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.

tau
+1  A: 

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.

Dawn