adding

S

Stuart

I am occasionally having problems with adding numbers together. Sometimes
(not always) 2 + 2 = 22, Obviousy this is a string issue. I am using the
following method to overcome this problem, however I feel it is a bit
contrived, and i am sure there is a proper way of doing it!

var asd = 2
var zxc=2
asd=asd-(-1*zxc)
 
L

Lasse Reichstein Nielsen

Stuart said:
I am occasionally having problems with adding numbers together. Sometimes
(not always) 2 + 2 = 22, Obviousy this is a string issue. I am using the
following method to overcome this problem, however I feel it is a bit
contrived, and i am sure there is a proper way of doing it!

<URL:http://jibbering.com/faq/#FAQ4_21>

/L
 
S

Svend Ezaki Tofte (DIKU)

I am occasionally having problems with adding numbers together. Sometimes
(not always) 2 + 2 = 22, Obviousy this is a string issue. I am using the
following method to overcome this problem, however I feel it is a bit
contrived, and i am sure there is a proper way of doing it!

If I want to force conversion, and I'm lazy, I go:

baz = 0 + foo + bar;

It's the same ideas as when you want to turn stuff into a string:

baz = "" + foo + bar;

But in general, 2 + 2 should /never/ give you 22. Unless you're pulling
the numbers from, say a input box (in which case you're pulling text!)

Regards,
Svend
 
L

Lasse Reichstein Nielsen

Svend Ezaki Tofte (DIKU) said:
If I want to force conversion, and I'm lazy, I go:

baz = 0 + foo + bar;

That would be *too* lazy.

var foo="2", bar="2";
alert(0 + foo + bar);

This alerts "022". The type concversion favors strings over numbers,
so when you add a string to a number, the number is converted to a
string, not the other way around. The order doesn't matter.

Just do as the FAQ says :) The fastest method is the unary prefix
plus.
var baz = +foo + +bar;
It's the same ideas as when you want to turn stuff into a string:

baz = "" + foo + bar;

Which works, because the string wins, and evaluation is left to right.

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in Svend Ezaki Tofte (DIKU)
If I want to force conversion, and I'm lazy, I go:

baz = 0 + foo + bar;

That's a nice easy method; the only fault, as far as I can see, is that
it does not work.

Tested solutions are safer.

Read the FAQ.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top