ECMAScript Type Conversion
- Previous Page ECMAScript Primitive Types
- Next Page ECMAScript Reference Types
One of the most important features of all programming languages is the ability to perform type conversions.
ECMAScript provides developers with a large number of simple type conversion methods.
Most types have methods for simple conversions, and there are also several global methods that can be used for more complex conversions. In any case, type conversion in ECMAScript is a brief one-step operation.
Convert to string
The interesting thing about the primitive values of Boolean, numbers, and strings in ECMAScript is that they are pseudo-objects, which means they actually have properties and methods.
For example, to get the length of a string, you can use the following code:
var sColor = "red"; alert(sColor.length); // Output '3'
Although 'red' is a primitive string type, it still has a property called length, which stores the size of the string.
In summary, the three main primitive types, Boolean values, numbers, and strings, all have toString() methods that can convert their values to strings.
Hint:You may ask, 'Does the string have a toString() method, isn't this redundant?' Yes, indeed, ECMAScript defines that all objects have a toString() method, whether they are pseudo-objects or true objects. Since the String type is a pseudo-object, it must have a toString() method.
The toString() method of the Boolean type simply outputs "true" or "false", with the result determined by the value of the variable:
var bFound = false; alert(bFound.toString()); // Outputs "false"
The toString() method of the Number type is quite special, as it has two modes, namelyDefault modeandBase patternThe toString() method, using the default mode, simply outputs the numeric value as a string (whether an integer, floating-point number, or in scientific notation), as shown below:
var iNum1 = 10; var iNum2 = 10.0; alert(iNum1.toString()); // Outputs "10" alert(iNum2.toString()); // Outputs "10"
Note:In the default mode, regardless of the representation used to declare the number initially, the toString() method of the Number type always returns the decimal representation of the number. Therefore, numbers declared in octal or hexadecimal literals are output in decimal form.
Using the base pattern of the toString() method of the Number type, you can use differentBaseOutput numbers, for example, the base of binary is 2, the base of octal is 8, and the base of hexadecimal is 16.
BaseIt is just another addition to convert to the base, which is the parameter of the toString() method:
var iNum = 10; alert(iNum.toString(2)); // Outputs "1010" alert(iNum.toString(8)); // Outputs "12" alert(iNum.toString(16)); // Outputs "A"
In the previous example, the number 10 was output in three different forms: binary, octal, and hexadecimal. HTML uses hexadecimal to represent each color, which is very useful when dealing with numbers in HTML.
Note:Calling toString(10) on a number is the same as calling toString(), both of which return the decimal form of the number.
See also:
Please refer to JavaScript Reference ManualDetailed information about the toString() method is provided:
Convert to number
ECMAScript provides two methods for converting non-numeric primitive values to numbers, namely parseInt() and parseFloat().
As you might expect, the former converts values to integers, and the latter converts values to floating-point numbers. These methods only work correctly when called on String types; when called on other types, they return NaN.
parseInt()
Before determining whether a string is a numeric value, parseInt() and parseFloat() both carefully analyze the string.
The parseInt() method first checks the character at position 0 to determine if it is a valid digit; if not, the method returns NaN and stops executing other operations. But if the character is a valid digit, the method will check the character at position 1, performing the same test. This process will continue until a non-valid digit character is found, at which point parseInt() will convert the string before this character to a number.
For example, if you want to convert the string "12345red" to an integer, parseInt() will return 12345, because when it checks the character r, it stops the detection process.
Numeric literals contained in strings are correctly converted to numbers, for example, "0xA" is correctly converted to the number 10. However, the string "22.5" will be converted to 22, because the decimal point is an invalid character for integers.
Here are some examples:
var iNum1 = parseInt("12345red"); //returns 12345 var iNum1 = parseInt("0xA"); //returns 10 var iNum1 = parseInt("56.9"); //returns 56 var iNum1 = parseInt("red"); //returns NaN
The parseInt() method also has a base mode, which can convert binary, octal, hexadecimal, or any other base string to an integer. The base is specified by the second parameter of parseInt(), so to parse hexadecimal values, you need to call the parseInt() method as follows:
var iNum1 = parseInt("AF", 16); //returns 175
Of course, you can call the parseInt() method in this way for binary, octal, even decimal (default mode):
var iNum1 = parseInt("10", 2); //returns 2 var iNum2 = parseInt("10", 8); //Returns 8 var iNum3 = parseInt("10", 10); //Returns 10
If the decimal number contains a leading 0, it is better to use base 10 so as not to get an unexpected octal value. For example:
var iNum1 = parseInt("010"); //Returns 8 var iNum2 = parseInt("010", 8); //Returns 8 var iNum3 = parseInt("010", 10); //Returns 10
In this code, both lines of code parse the string "010" as a number. The first line treats the string as an octal value, parsing it in the same way as the second line (declare the base as 8). The last line declares the base as 10, so iNum3 finally equals 10.
See
Please refer to JavaScript Reference ManualThe following is detailed information about the parseInt() method:parseInt().
parseFloat()
The parseFloat() method handles similar to the parseInt() method, starting from position 0 to view each character until the first non-valid character is found, and then convert the string before that character to an integer.
However, for this method, the first decimal point encountered is a valid character. If there are two decimal points, the second decimal point is considered invalid. parseFloat() will convert the characters before the decimal point to a number. This means that the string "11.22.33" will be parsed as 11.22.
Another difference in using the parseFloat() method is that the string must represent the floating-point number in decimal form, not in octal or hexadecimal. This method ignores leading 0s, so the octal number 0102 will be parsed as 102. For the hexadecimal number 0xA, this method will return NaN, because in floating-point numbers, x is not a valid character. (Note:According to testing, the specific browser implementation will return 0 instead of NaN.)
Additionally, the parseFloat() method does not have a base mode.
Here are some examples of using the parseFloat() method:
var fNum1 = parseFloat("12345red"); //Returns 12345 var fNum2 = parseFloat("0xA"); //Returns NaN var fNum3 = parseFloat("11.2"); //Returns 11.2 var fNum4 = parseFloat("11.22.33"); //Returns 11.22 var fNum5 = parseFloat("0102"); // returns 102 var fNum1 = parseFloat("red"); // returns NaN
See
Please refer to JavaScript Reference ManualThe following is detailed information about the parseFloat() method provided:parseFloat().
type coercion
You can also useType coercion (type casting)to handle the type of the converted value. Type coercion can be used to access specific values even if they are of another type.
Editor's note:The word 'cast' means 'casting', which is very fitting for the meaning of 'type coercion'.
The 3 types of type coercion available in ECMAScript are as follows:
- Boolean(value) - Convert the given value to a Boolean type;
- Number(value) - Convert the given value to a number (which can be an integer or a floating-point number);
- String(value) - Convert the given value to a string;
Using one of these three functions to convert a value will create a new value, storing the value directly converted from the original value. This can cause unexpected consequences.
Boolean() function
When the value to be converted is a string with at least one character, a non-zero number, or an object, the Boolean() function will return true. If the value is an empty string, number 0, undefined, or null, it will return false.
You can test the type coercion of Boolean type with the following code:
var b1 = Boolean(""); // false - empty string var b2 = Boolean("hello"); // true - non-empty string var b1 = Boolean(50); // true - non-zero number var b1 = Boolean(null); // false - null var b1 = Boolean(0); // false - zero var b1 = Boolean(new object()); // true - object
Number() function
The type coercion of the Number() function is similar to that of the parseInt() and parseFloat() methods, but it converts the entire value, not just a part of it.
Remember that the parseInt() and parseFloat() methods only convert the string before the first invalid character, so "1.2.3" will be converted to "1" and "1.2" respectively.
When using Number() for type coercion, "1.2.3" will return NaN because the entire string value cannot be converted to a number. If the string value can be fully converted, Number() will determine whether to call the parseInt() method or the parseFloat() method.
The following table explains what happens when the Number() method is called with different values:
Usage | Result |
---|---|
Number(false) | 0 |
Number(true) | 1 |
Number(undefined) | NaN |
Number(null) | 0 |
Number("1.2") | 1.2 |
Number("12") | 12 |
Number("1.2.3") | NaN |
Number(new object()) | NaN |
Number(50) | 50 |
String() function
The last type coercion method, String(), is the simplest because it can convert any value to a string.
To perform this type coercion, you just need to call the toString() method of the value passed as a parameter, i.e., convert 12 to "12", convert true to "true", convert false to "false", and so on.
The only difference between type coercion to a string and calling the toString() method is that type coercion of null and undefined values can generate a string without causing an error:
var s1 = String(null); //"null" var oNull = null; var s2 = oNull.toString(); //This will cause an error
Type coercion is very useful when dealing with weakly typed languages like ECMAScript, but it should ensure that the value used is correct.
- Previous Page ECMAScript Primitive Types
- Next Page ECMAScript Reference Types