JavaScript Tutorial/Number Data Type/Type Conversion

Материал из Web эксперт
Перейти к: навигация, поиск

Casting to Boolean value

The Boolean() type cast returns true when

the value is a string with at least one character,

a number other than 0, or

an object;

The Boolean() type cast returns false when

  1. the value is an empty string,
  2. the number 0,
  3. undefined, or
  4. null.



   <source lang="javascript">

var b1 = Boolean(""); //false -- empty string var b2 = Boolean("JavaScript"); //true -- non-empty string var b3 = Boolean(100); //true -- non-zero number var b4 = Boolean(null); //false -- null var b5 = Boolean(0); //false -- zero var b6 = Boolean(new Object()); //true -- object</source>


Casting to Number

The Number() type cast works in a manner similar to parseInt() and parseFloat().

Except that it converts the entire value, not just part of it.

parseInt() and parseFloat() only convert up to the first invalid character (in strings),so "4.5.6" becomes "4.5".

Using the Number() type cast, "4.5.6".

If a string value can be converted entirely, Number() decides whether to use parseInt() or parseFloat().

Usage Result Number(false) 0 Number(true) 1 Number(undefined) NaN Number(null) 0 Number("5.5") 5.5 Number("56") 56 Number("5.6.7") NaN Number(new Object()) NaN Number(100) 100

Casting type to string

When casting type to string, JavaScript simply calls the toString() method.

The type cast can produce a string for a null or undefined value without error.



   <source lang="javascript">

var s1 = String(null); //"null" var oNull = null; var s2 = oNull.toString(); //won"t work, causes an error</source>


Converting to a Number

JavaScript has two methods for converting non-number primitives into numbers: parseInt() and parseFloat().

parseInt() converts a value into an integer.

parseFloat() converts a value into a floating-point number.

These methods only work properly when called on strings; all other types return NaN.

5. 8. Type Conversion 5. 8. 1. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/TypeConversion.htm">Type Conversion</a> 5. 8. 2. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Typeconversionadherestothefollowingrules.htm">Type-conversion adheres to the following rules</a> 5. 8. 3. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaString.htm">Converting to a String</a> 5. 8. 4. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/UsingNumberstoStringmethodinradixmode.htm">Using Number"s toString() method in radix mode</a> 5. 8. 5. Converting to a Number 5. 8. 6. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntmethod.htm">parseInt() method</a> 5. 8. 7. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntinradixmode.htm">parseInt() in radix mode</a> 5. 8. 8. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Ifdecimalnumberscontainaleadingzeroitsalwaysbesttospecifytheradixas10sothatyouwontaccidentallyendupwithanoctalvalue.htm">If decimal numbers contain a leading zero, it"s always best to specify the radix as 10 so that you won"t accidentally end up with an octal value.</a> 5. 8. 9. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloatmethod.htm">parseFloat() method</a> 5. 8. 10. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/TypeCasting.htm">Type Casting</a> 5. 8. 11. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoBooleanvalue.htm">Casting to Boolean value</a> 5. 8. 12. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoNumber.htm">Casting to Number</a> 5. 8. 13. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Castingtypetostring.htm">Casting type to string</a> 5. 8. 14. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseInt3300.htm">parseInt("33.00")</a> 5. 8. 15. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat123e2.htm">parseFloat("1.23e-2")</a> 5. 8. 16. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat145inch.htm">parseFloat("1.45inch")</a>

Converting to a String

Booleans, numbers, and strings all have a toString() method to convert their value to a string.

The Boolean toString() method simply outputs the string "true" or "false".



   <source lang="javascript">

var bFound = false; alert(bFound.toString()); //outputs "false"</source>


If decimal numbers contain a leading zero, it"s always best to specify the radix as 10 so that you won"t accidentally end up with an octal value.

   <source lang="javascript">

var iNum1 = parseInt("010"); //returns 8 var iNum2 = parseInt("010", 8); //returns 8 var iNum3 = parseInt("010", 10); //returns 10</source>


parseFloat("1.23e-2")

   <source lang="javascript">

<html> <head> <title>Convert String to Number</title> </head> <body>

<script type="text/javascript"> var sNum = "1.23e-2"; document.writeln(parseFloat(sNum)); </script>

</body> </html></source>


parseFloat("1.45inch")

   <source lang="javascript">

<html> <head> <title>Convert String to Number</title> </head> <body>

<script type="text/javascript"> var fValue = parseFloat("1.45inch"); document.writeln("<p>" + fValue + "

");

</script> </p> </body> </html></source>


parseFloat() method

The parseFloat() method starts in position 0.

It continues until the first invalid character and then converts the string it has seen up to that point.

The decimal point is a valid character the first time it appears.

The string "22.34.5" will be parsed into 22.34.

The string must represent a floating-point number in decimal form, not octal or hexadecimal.

This method ignores leading zeros.

The hexadecimal number 0xA will return NaN because x isn"t a valid character for a floating-point number.

There is also no radix mode for parseFloat().



   <source lang="javascript">

var fNum1 = parseFloat("1234AAA"); var fNum2 = parseFloat("0xA"); var fNum3 = parseFloat("2.5"); var fNum4 = parseFloat("2.34.5"); var fNum5 = parseFloat("0908"); var fNum6 = parseFloat("blue");</source>


parseInt("33.00")

   <source lang="javascript">

<html> <head> <title>Convert String to Number</title> </head> <body>

<script type="text/javascript"> var iValue = parseInt("33.00"); document.writeln("<p>" + iValue + "

");

</script> </p> </body> </html></source>


parseInt() in radix mode

The parseInt() method also has a radix mode, allowing you to convert strings in binary, octal, hexadecimal, or any other base into an integer.

The radix is specified as a second argument to parseInt().



   <source lang="javascript">

var iNum1 = parseInt("AF", 16); var iNum1 = parseInt("10", 2); var iNum2 = parseInt("10", 8); var iNum2 = parseInt("10", 10);</source>


parseInt() method

The parseInt() method starts with the character in position 0 and determines if this is a valid number

If it isn"t, the method returns NaN and doesn"t continue.

If it is valid, the method goes on to the character in position 1.

This process continues until a character isn"t a valid number.

parseInt() takes the string up to that point and converts it into a number.

parseInt("1234AAA") returns 1234 because it stops processing one it reaches the character A.

Any number literal contained in a string is also converted correctly.

The string "0xA" is properly converted into the number 10.

The string "22.5" will be converted to 22, because the decimal point is an invalid character for an integer.



   <source lang="javascript">

var iNum1 = parseInt("1234blue"); var iNum2 = parseInt("0xA"); var iNum3 = parseInt("22.5"); var iNum4 = parseInt("blue");</source>


Type Casting

Type casting allows you to access a specific value as if it were of a different type.

Three type casts are available in JavaScript:

Boolean(value) -- casts the given value as a Boolean

Number(value) -- casts the given value as a number (either integer or floating-point)

String(value) -- casts the given value a string

5. 8. Type Conversion 5. 8. 1. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/TypeConversion.htm">Type Conversion</a> 5. 8. 2. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Typeconversionadherestothefollowingrules.htm">Type-conversion adheres to the following rules</a> 5. 8. 3. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaString.htm">Converting to a String</a> 5. 8. 4. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/UsingNumberstoStringmethodinradixmode.htm">Using Number"s toString() method in radix mode</a> 5. 8. 5. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaNumber.htm">Converting to a Number</a> 5. 8. 6. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntmethod.htm">parseInt() method</a> 5. 8. 7. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntinradixmode.htm">parseInt() in radix mode</a> 5. 8. 8. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Ifdecimalnumberscontainaleadingzeroitsalwaysbesttospecifytheradixas10sothatyouwontaccidentallyendupwithanoctalvalue.htm">If decimal numbers contain a leading zero, it"s always best to specify the radix as 10 so that you won"t accidentally end up with an octal value.</a> 5. 8. 9. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloatmethod.htm">parseFloat() method</a> 5. 8. 10. Type Casting 5. 8. 11. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoBooleanvalue.htm">Casting to Boolean value</a> 5. 8. 12. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoNumber.htm">Casting to Number</a> 5. 8. 13. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Castingtypetostring.htm">Casting type to string</a> 5. 8. 14. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseInt3300.htm">parseInt("33.00")</a> 5. 8. 15. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat123e2.htm">parseFloat("1.23e-2")</a> 5. 8. 16. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat145inch.htm">parseFloat("1.45inch")</a>

Type Conversion

JavaScript allows a variable to hold any data type at any time.

A variable can be assigned a string initially and then be reassigned to an integer.

JavaScript also attempts to perform all necessary type conversions.

5. 8. Type Conversion 5. 8. 1. Type Conversion 5. 8. 2. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Typeconversionadherestothefollowingrules.htm">Type-conversion adheres to the following rules</a> 5. 8. 3. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaString.htm">Converting to a String</a> 5. 8. 4. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/UsingNumberstoStringmethodinradixmode.htm">Using Number"s toString() method in radix mode</a> 5. 8. 5. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaNumber.htm">Converting to a Number</a> 5. 8. 6. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntmethod.htm">parseInt() method</a> 5. 8. 7. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntinradixmode.htm">parseInt() in radix mode</a> 5. 8. 8. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Ifdecimalnumberscontainaleadingzeroitsalwaysbesttospecifytheradixas10sothatyouwontaccidentallyendupwithanoctalvalue.htm">If decimal numbers contain a leading zero, it"s always best to specify the radix as 10 so that you won"t accidentally end up with an octal value.</a> 5. 8. 9. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloatmethod.htm">parseFloat() method</a> 5. 8. 10. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/TypeCasting.htm">Type Casting</a> 5. 8. 11. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoBooleanvalue.htm">Casting to Boolean value</a> 5. 8. 12. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoNumber.htm">Casting to Number</a> 5. 8. 13. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Castingtypetostring.htm">Casting type to string</a> 5. 8. 14. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseInt3300.htm">parseInt("33.00")</a> 5. 8. 15. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat123e2.htm">parseFloat("1.23e-2")</a> 5. 8. 16. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat145inch.htm">parseFloat("1.45inch")</a>

Type-conversion adheres to the following rules

true is converted to the number 1 before being compared.

false is converted to 0 before being compared.

If either of the operands are NaN, the equality operator returns false.

null and undefined are equal.

null and undefined are not equal to 0 (zero), "" , or false.

If a string and a number are compared, attempt to convert the string to a number and then check for equality.

If an object and a string are compared, attempt to convert the object to a string and then check for equality.

If an object and a number are compared, attempt to convert the object to a number and then check for equality.

If both operands of an equality operation are objects, the addresses of the two objects are checked for equality.

Quote from:

Pure JavaScript (Paperback)

by R. Allen Wyke (Author), Jason Gilliam (Author), Charlton Ting (Author)

# Paperback: 1448 pages

# Publisher: Sams; 1st edition (August 1999)

# Language: English

# ISBN-10: 0672315475

# ISBN-13: 978-0672315473

5. 8. Type Conversion 5. 8. 1. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/TypeConversion.htm">Type Conversion</a> 5. 8. 2. Type-conversion adheres to the following rules 5. 8. 3. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaString.htm">Converting to a String</a> 5. 8. 4. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/UsingNumberstoStringmethodinradixmode.htm">Using Number"s toString() method in radix mode</a> 5. 8. 5. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/ConvertingtoaNumber.htm">Converting to a Number</a> 5. 8. 6. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntmethod.htm">parseInt() method</a> 5. 8. 7. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseIntinradixmode.htm">parseInt() in radix mode</a> 5. 8. 8. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Ifdecimalnumberscontainaleadingzeroitsalwaysbesttospecifytheradixas10sothatyouwontaccidentallyendupwithanoctalvalue.htm">If decimal numbers contain a leading zero, it"s always best to specify the radix as 10 so that you won"t accidentally end up with an octal value.</a> 5. 8. 9. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloatmethod.htm">parseFloat() method</a> 5. 8. 10. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/TypeCasting.htm">Type Casting</a> 5. 8. 11. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoBooleanvalue.htm">Casting to Boolean value</a> 5. 8. 12. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/CastingtoNumber.htm">Casting to Number</a> 5. 8. 13. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/Castingtypetostring.htm">Casting type to string</a> 5. 8. 14. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseInt3300.htm">parseInt("33.00")</a> 5. 8. 15. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat123e2.htm">parseFloat("1.23e-2")</a> 5. 8. 16. <A href="/Tutorial/JavaScript/0100__Number-Data-Type/parseFloat145inch.htm">parseFloat("1.45inch")</a>

Using Number"s toString() method in radix mode

When using Number"s toString() method in radix mode, it is possible to output the number using a different base, such as 2 for binary, 8 for octal, or 16 for hexadecimal.

This functionality is useful for dealing with numbers in HTML.

HTML uses hexadecimal representations for each color.



   <source lang="javascript">

var iNum = 10; alert(iNum1.toString(2)); alert(iNum1.toString(8)); alert(iNum1.toString(16));</source>