473,760 Members | 10,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number? (2007-12-31)

-----------------------------------------------------------------------
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: ` +varname ` or ` Number(varname) ` or
` parseInt(varnam e, 10) ` or ` parseFloat(varn ame) `.
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_not...e_convert.html

http://msdn.microsoft.com/library/de...7c6cd2a248.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.javas cript FAQ is at http://jibbering.com/faq/index.html.
The FAQ workers are a group of volunteers. The sendings of these
daily posts are proficiently hosted by http://www.pair.com.

Dec 31 '07 #1
2 2228
In comp.lang.javas cript message <47************ ***********@new s.sunsite.
dk>, Mon, 31 Dec 2007 00:00:02, FAQ server <ja********@dot internet.be>
posted:
>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.
Not a helpful way of starting, when the situation is that the conversion
needed by the coder does NOT happen.
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: ` +varname ` or ` Number(varname) ` or
` parseInt(varnam e, 10) ` or ` parseFloat(varn ame) `.
Prompt and form control values are strings, as is the result from
a prompt window. Convert these to numbers before performing addition.

Javascript variables are not typed by declaration, but are variants
typed by content; the type (String, Number, Boolean, ...) is stored, as
well as the ostensible value.

Prompt and form control values are of type String, as is the result from
a prompt window. They must be converted to Number for arithmetic.

Type conversion happens automatically, as required for the operator.
For example, the two operands of star (*) are always used as Numbers.

Plus (+), with two operands, is used both for addition and for string
concatenation. It is a language feature that concatenation occurs
unless each operand is already Number or Boolean - so ` 1 + 2 ` gives `
3 ` and ` 1 + true ` gives ` 2 ` but ` "1" + 2 ` gives ` "12" `.
However, unary plus, prefixing a single operand of any type, always
results in a Number (maybe NaN); so ` +"1" + 2 ` and ` 1 + +"2" ` and `
+"1" + +"2" ` give ` 3 `.

A decimal string, perhaps with leading and/or trailing whitespace, is
best converted by ` +varname ` or ` Number(varname) `. A decimal string
which may have visible trailing characters is converted by
` parseInt(varnam e, 10) ` or ` parseFloat(varn ame) `.
/* That needs consideration to verify that all statements are exactly
true whatever types, including Boolean, Function, Object, are used.
I've checked, for example, LZ*3 and LZ+3 with LZ a function. */

Note : with ` ` used as above, it is better to use " rather than ' for
strings.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)
Dec 31 '07 #2
In comp.lang.javas cript message <Nq************ *********@gigan ews.com>,
Tue, 1 Jan 2008 12:00:41, Randy Webb <Hi************ @aol.composted:
>Dr J R Stockton said the following on 12/31/2007 4:02 PM:
> Javascript variables are not typed by declaration, but are variants
typed by content; the type (String, Number, Boolean, ...) is stored, as
well as the ostensible value.

I don't agree with that. They are typed by how they are declared. If
you want a different type, then you have to either declare it
differently or convert it. Either automatically or intentionally.
In a declaration such as the one in
function X() { var J ; alert(9+J) }
variable J is not usefully typed (OK, "undefined" is a type).

In Javascript the type of a variable is set by its most recent
assignment.

Intentional conversion of a variable, as in S = "66" ; S = +S ; is
by reassignment. In T = +S + 2 ; the type of S is not changed. The
value taken from it is changed, by the unary +, to type Number.

Granted that my wording needs minor upgrade to accommodate var J=0; .

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demo n.co.uk/clpb-faq.txt RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zipTimo Salmi's Turbo Pascal FAQ.
Jan 1 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3434
by: Allerdyce.John | last post by:
Do I need to convert string to integer in python? or it will do it for me (since dynamic type)? In my python script, I have this line: x /= 10; when i run it, I get this error: TypeError: unsupported operand type(s) for /=: 'unicode' and 'int' I want to divide x by 10 and assign that value back to x.
1
2238
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ 3.5. - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly.
52
1565
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly.
19
3610
by: VK | last post by:
http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/ b495b4898808fde0> is more than one month old - this may pose problem for posting over some news servers. This is why I'm starting a new one] I'd still like to finish this rounding mess. As a startup lemma we can take that VK is the worst programmer of all times and places: let's move from here forward please. The usability of any program depends on exact behavior...
11
12339
by: davidj411 | last post by:
i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of numbers and add up the totals for each number. on the bill, each line has a few fields,one field containing the phone number, another field containing the number of minutes on that call. the bill is comma delimited.
10
1863
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly. See section 4.7 for Rounding issues.
1
1378
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly. See section 4.7 for Rounding issues.
2
3094
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? ----------------------------------------------------------------------- When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00? Rounding of x.xx5 is uncertain, as such numbers are not represented exactly. See the section on "simple decimal...
4
7225
subedimite
by: subedimite | last post by:
Here I am with another question being a very new VBA user. I have this scenario to work with: I would think this is fairly common routine of work for VBA. I have a string of hex contents as characters such as String1 = “3B F0 96 00 FF C0 0A 31 FE 4D D1” I need to do some calculation with these and then update a table with the text value. For example, A sum of all these.
0
9521
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10107
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9900
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9765
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7324
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6599
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5361
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3863
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3442
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.