F
FAQ server
-----------------------------------------------------------------------
FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?
-----------------------------------------------------------------------
Javascript variables are loosely typed: the conversion between a
string and a number happens automatically. Since plus (+) is also
used as in string concatenation, « '1' + 1 » is equal to « '11' »: the
String deciding what + does. To overcome this, first convert the
string to a number. For example:
« Number(varname) » or « varname*1 » or « varname-0 » or
« parseInt(varname, 10) » or « parseFloat(varname) » or « +varname ».
Prompt and form control values are strings, as is the result from
a prompt window. Convert these to numbers before performing
addition.
Additional Notes:
http://www.jibbering.com/faq/faq_notes/type_convert.html
http://msdn.microsoft.com/library/en-us/script56/html/js56jscondeclare.asp
===
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://www.jibbering.com/faq/.
The FAQ workers are a group of volunteers.
FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?
-----------------------------------------------------------------------
Javascript variables are loosely typed: the conversion between a
string and a number happens automatically. Since plus (+) is also
used as in string concatenation, « '1' + 1 » is equal to « '11' »: the
String deciding what + does. To overcome this, first convert the
string to a number. For example:
« Number(varname) » or « varname*1 » or « varname-0 » or
« parseInt(varname, 10) » or « parseFloat(varname) » or « +varname ».
Prompt and form control values are strings, as is the result from
a prompt window. Convert these to numbers before performing
addition.
Additional Notes:
http://www.jibbering.com/faq/faq_notes/type_convert.html
http://msdn.microsoft.com/library/en-us/script56/html/js56jscondeclare.asp
===
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://www.jibbering.com/faq/.
The FAQ workers are a group of volunteers.