Shoutbox

help with convert strings - Printable Version

-Shoutbox (https://shoutbox.menthix.net)
+-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58)
+--- Forum: Messenger Plus! for Live Messenger (/forumdisplay.php?fid=4)
+---- Forum: Scripting (/forumdisplay.php?fid=39)
+----- Thread: help with convert strings (/showthread.php?tid=95200)

help with convert strings by ChaosMaker on 08-08-2010 at 04:23 AM

hi all, i want convert strings to numbers
i´m using this
var number1='5';
var number2='4';
var result=number1+number2;
Messenger.MyPersonalMessage=result
but the result is 54, and not 9. why ?
how can i convert '5' to 5 ?


RE: help with convert strings by Adeptus on 08-08-2010 at 06:00 AM

quote:
var number1='5';
var number2='4';
var result=number1+number2;
...
but the result is 54, and not 9. why ?
To answer your question for your specific example: because you have indicated the values are strings by using single quotes.  Remove the quotes and try the following:
code:
var number1 = 5;
var number2 = 4;
var result = number1 + number2;
Now you should be getting 9 as the result. 

Of course, you won't always be able to do this when your values are coming from somewhere else and happen to be strings.  When that happens you will want to check out parseInt() and parseFloat():
code:
var number1 = '5';
var number2 = '4';
var result = parseInt(number1) + parseInt(number2);
This should yield 9 as well.
RE: help with convert strings by Spunky on 08-08-2010 at 01:34 PM

In addition to that, a trick I tend to use is:

Javascript code:
var number1 = '5';
var number2 = '4';
var result = (number1 * 1) + (number2 * 1);


The brackets shouldn't be needed, but I use them anyway
RE: help with convert strings by NanaFreak on 08-08-2010 at 02:19 PM

quote:
Originally posted by Spunky
Javascript code:
var result = (number1 * 1) + (number2 * 2);



shouldnt the second one be * 1 still? :P
RE: help with convert strings by Spunky on 08-08-2010 at 07:29 PM

Yeah, I was in a rush going out...