1

I have the following piece of code:

if(netAnnualBilling == null){
                        netAnnualBilling = 0;
                        parseFloat(netAnnualBilling);
                }
                parseFloat(netAnnualBilling);
                annualBillingCount = (annualBillingCount + netAnnualBilling);
                parseFloat(annualBillingCount);

My two variables netAnnualBilling and annualBillingCount are both of type numbers. However, when I get to this line:

            annualBillingCount = (annualBillingCount + netAnnualBilling);

javascript seems to turn annualBillingCount into type String and appends the two numbers together instead of adding or subtracting as its supposed to. Example:

annualBillingCount = 0; 
netAnnualBilling = -1403.30
The result of the above code will show annualBillingCount to be equal to : 0-1403.80 

I've tried ParseFloat every time these variables pop up but I'm not having any luck. What's going on?

1
  • 1
    Hmm, are you certain both are numbers? If they truly are, the addition will produce a number, not a string. Try it in the console. Commented Oct 21, 2013 at 14:06

3 Answers 3

6

If you want to make sure the variables are used as numbers, you can simply prepend the unary plus operator:

annualBillingCount = +annualBillingCount + +netAnnualBilling;

will force each operand to be treated as a number.

EDIT Heres a basic fiddle showing the addition of two strings with varying uses of the unary casting, using the code below:

var onetwo = "12";
var threefour = "34";

alert(onetwo + threefour); // string + string, so "12" + "34" = "1234"
alert(+onetwo + threefour); // number + string, so 12 + "34" = "12" + "34" = "1234"
alert(onetwo + +threefour); // string + number, second will be coerced back to string, so "12" + "34" = "1234"
alert(+onetwo + +threefour); // number + number, so 12 + 34 = 46
Sign up to request clarification or add additional context in comments.

1 Comment

This worked too. Unfortunately the IDE i'm using (Aptana) gives JsLint warnings when putting two + signs next to each other and I was unfortunately unable to use this. But great info for the future!
1

parseFloat() doesn't change the value, it returns the casted value. You need:

netAnnualBilling = parseFloat(netAnnualBilling)

1 Comment

Thanks. That's what I was missing, setting the parseFloat to a variable.
0

Try this:

if(netAnnualBilling == null) {
     netAnnualBilling = 0;
}
netAnnualBilling = parseFloat(netAnnualBilling);
annualBillingCount = parseFloat(annualBillingCount);
annualBillingCount += netAnnualBilling;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.