Converting numbers to strings

Converting numbers to strings

Postby lucian0308 » Thu 28 May 2009, 03:26

You’ll have less need for converting a number to its string equivalent than the other way
around. As you saw in the previous section, JavaScript gravitates toward strings when faced
with an expression containing mixed data types. Even so, it is good practice to perform data
type conversions explicitly in your code to prevent any potential ambiguity. The simplest way
to convert a number to a string is to take advantage of JavaScript’s string tendencies in addition
operations. By adding an empty string to a number, you convert the number to its string
equivalent:
(“” + 2500) // result = “2500”
(“” + 2500).length // result = 4
In the second example, you can see the power of expression evaluation at work. The parentheses
force the conversion of the number to a string. A string is a JavaScript object that has
properties *censored* with it. One of those properties is the length property, which evaluates
to the number of characters in the string. Therefore, the length of the string “2500” is 4.
Note that the length value is a number, not a string.


-------------------------------------------
Admin of this site!!!
-------------------------------------------
lucian0308
Administratorul
 
Posts: 53
Joined: Sat 02 Aug 2008, 19:18
Location: bucuresti

Return to JavaScript

Who is online

Users browsing this forum: No registered users and 0 guests

cron