There are three main methods
Conversion function, forced type conversion, and weak type conversion using js variables.
1. Conversion function:
js provides two conversion functions, parseInt() and parseFloat(). The former converts the value to an integer, and the latter converts the value to a floating point number. Only by calling these methods on the String type can these two functions run correctly; for other types, NaN (Not a Number) is returned.
Some examples are as follows:
The parseInt() method also has a base mode, which can convert binary, octal, hexadecimal or any other base string into an integer. The base is specified by the second parameter of the parseInt() method. An example is as follows:
If a decimal number contains leading 0s, it's better to use base 10 so you don't accidentally get an octal value. For example:
The parseFloat() method is handled similarly to the parseInt() method.
Another difference in using the parseFloat() method is that the string must represent a floating point number in decimal form, and parseFloat() has no base mode.
The following is an example of using the parseFloat() method:
2. Forced type conversion
You can also use type casting to handle the type of converted values. Use a cast to access a specific value, even if it is of another type.
The three types of casts available in ECMAScript are as follows:
Boolean(value) - Convert the given value into Boolean type;
Number(value) - Convert the given value into a number (Can be an integer or floating point number);
String(value) - Convert the given value into a string.
Converting a value using one of these three functions will create a new value that stores the value directly converted from the original value. This can have unintended consequences.
The Boolean() function returns true when the value to be converted is a string, non-zero number, or object with at least one character (this will be discussed in the next section). If the value is an empty string, the number 0, undefined, or null, it returns false.
You can use the following code snippet to test Boolean type cast.
The coercion of Number() is similar to the parseInt() and parseFloat() methods, except that it converts the entire value instead of part of the value. An example is as follows:
Give me a small example, you will understand after you look at it.