Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

objectName is the object to convert to a string, whereas radix is the base to use for representing numeric values when the calling object is a number. The following example prints the string equivalents of the numbers 0 through 9 in decimal and binary:

for (x = 0; x < 10; x++) {
   document.write("Decimal: ", x.toString(10), " Binary: ",
x.toString(2), "<BR>")
}

The loop’s output is:


Decimal: 0 Binary: 0
Decimal: 1 Binary: 1
Decimal: 2 Binary: 10
Decimal: 3 Binary: 11
Decimal: 4 Binary: 100
Decimal: 5 Binary: 101
Decimal: 6 Binary: 110
Decimal: 7 Binary: 111
Decimal: 8 Binary: 1000
Decimal: 9 Binary: 1001

All objects, numbers included, have a toString() method. If an object has no string value, the method returns “[object type]”, where type is the object type (e.g., Date, Array, Object (user defined), Image). When used with an array, toString() joins the array elements and returns one string where elements are separated by commas. This operation is exactly like the join() method which concatenates the elements with a specified delimiter, possibly a comma.

For functions, toString() decompiles the function back into a canonical source string. Take a look at the following script segment:

function foo() {
 var a = 5
 alert(a)
 document.write("wow")
}
document.write(foo.toString())

The script’s output is:

function foo() { var a = 5; alert(a); document.write("wow"); }

String-to-Number Conversion

Mathematical operators, for example, accept numeric strings as operands and handle them fine. Here is an example for such an operation:

var num1= "7"
var num2 = "2"
var result = num1 – num2
document.write(result)

This script prints 5, just as if both variables were assigned a plain numeric value rather than a numeric string (we use the term numeric string to characterize a string that encloses a number, such as “911”). An operation consisting of numeric string operands returns a plain numeric value, not a string. Therefore, you can theoretically convert a numeric string to a number by performing an arithmetical operation on it. If you want, you can even use a function to execute the conversion in the following form:

function convert(val) {
  return val – 0
}
var num = "911"
num = convert(num)

Note that you cannot use the plus (+) operator because it is also a string concatenation operator in JavaScript. If you are not sure whether or not a value is a numeric string or a number, always convert it. It’s better to stay on the safe side than to spend hours searching for such errors. Conversion via mathematical operations is somewhat annoying, because it looks like a workaround. Therefore JavaScript provides us with a few conversion functions, each with its own attributes.

parseInt() and parseFloat()

These two functions were briefly discussed in Chapter 15, JavaScript Math. They are built-in functions, so they do not belong to any object. They convert their argument from a numeric string to a number. If the argument is a string but not a numeric one, the function returns zero. The parseFloat() function is more general, because it works with floating point numbers as well as integers. The parseInt() function works with integers only, and returns a rounded-off value when called with a floating point numeric string. Both functions return the value they are given if it is a plain number, not a numeric string. Therefore, if you are not sure whether a value is a number or a numeric string, simply send it to the function.

If a certain value in the script has a chance to be a floating point number, use parseFloat. It will also work if the value is an integer.

Here are a few expressions to demonstrate these functions, along with returned values:

parseInt("16") // 16
parseInt("16.33") // 16
parseFloat("16") // 16
parseFloat("16.33") // 16.33
parseInt("Howdy!") // 0

These functions are very useful when accepting input from the user via forms or prompts, because they always return a string, even if it represents a number.

Note that both functions return zero when the argument is a Boolean value. Therefore, if you want to check if the user canceled a prompt box by pressing the Cancel button, you must evaluate the condition before parsing the value. Here is an example:

var num = prompt("Enter a number between 0 and 9:")
if (num = false)
 alert("You must enter a value to continue.")
else
 num = parseInt(num)

A common but mistaken practice is to parse the value immediately. The result is that you cannot check if the user canceled the box, because he or she might have entered the number 0, which is parsed to the same value as a Boolean value.

Checking if a Value is a Number or Not

The isNaN() function evaluates an argument to determine if it is not a number, or “NaN.” Netscape Navigator 2.0 supports this function on Unix platforms only, but Navigator 3.0 fully implements it on all platforms.

The functions parseFloat() and parseInt() return “NaN” when they evaluate a value that is not a number or a numeric string. “NaN” is not a number in any string. If “NaN” is passed on to arithmetic operations, the result is also “NaN.” The isNaN() returns a Boolean value, according to the argument. Bear in mind that MSIE 3.0 does not support this feature—parseFloat() and parseInt() both return 0 if their argument is neither a string nor a numeric string.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us