JS parseint () and parsefloat (), number (), Boolean (), String () conversion

Source: Internet
Author: User

JS converts a string to a numeric value in three main ways

Conversion functions, coercion type conversion, the use of JS variable weak type conversion.

1. Conversion function:

JS provides the parseint () and parsefloat () two conversion functions. The former converts the value to an integer, and the latter converts the value to a floating-point number. These methods are invoked only on the string type, and the two functions are run correctly, and all other types are returned as Nan (not a number).

parseint () and parsefloat () parse the string carefully before deciding whether the string is a numeric value.

The parseint () method first looks at the character at position 0 to determine whether it is a valid number, and if not, the method returns Nan and does not continue with other operations. However, if the character is a valid number, the method will look at the characters at position 1 and do the same test. This process continues until a character is found that is not a valid number, at which point parseint () converts the string before the character to a number.

For example, if you want to convert the string "1234blue" to an integer, then parseint () will return 1234, because when it detects character B, it stops the detection process.

The literal number contained in the string is converted to numbers correctly, so the string "0xA" is correctly converted to Number 10.

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

Some examples are as follows:

JS code parseint ("1234blue");   Returns 1234 parseint ("0xA");   Returns parseint ("22.5");   Returns parseint ("Blue"); Returns NaN

The parseint () method also has a base pattern that converts binary, octal, hexadecimal, or any other string of strings into integers.

The base is specified by the second parameter of the parseint () method, so to parse the hexadecimal value, you need to invoke the parseint () method as follows: JS code parseint ("AF", 16); Returns 175

Of course, for binary, octal, or even decimal (default mode), you can call the parseint () method:

JS Code parseint ("10", 2);   Returns 2 parseint ("10", 8);   Returns 8 parseint ("10", 10); Returns 10

If the decimal number contains a leading 0, it is best to use cardinality 10 so that you do not accidentally get the octal value. For example:

JS code parseint ("010");   Returns 8 parseint ("010", 8);   Returns 8 parseint ("010", 10); Returns 10

In this code, two lines of code parse the string "010" into a number. The first line of code regards this string as a octal value, parsing it in the same way as the second line of code (the Declaration cardinality is 8). The last line of code declares a cardinality of 10, so the iNum3 finally equals 10.

The parsefloat () method is similar to the parseint () method, viewing each character starting at position 0 until the first inactive character is found, and then converting the string before the character to a number.

However, for this method, the first decimal point that appears is a valid character. If you have two decimal points, the second decimal point will be considered invalid, and the Parsefloat () method converts the string before the decimal point to a number. This means that the string "22.34.5" will be parsed into 22.34.

Another difference between using the Parsefloat () method is that the string must represent a floating-point number in decimal form, not in octal or hexadecimal form.

The method ignores leading 0, so the octal number 0908 will be resolved to 908. For hexadecimal 0xA, the method returns Nan, because x is not a valid character in a floating-point number.

In addition, parsefloat () also has no base mode.

The following is an example of using the Parsefloat () method: JS code parsefloat ("1234blue");   Returns 1234.0 parsefloat ("0xA");   Returns NaN parsefloat ("22.5");   Returns 22.5 parsefloat ("22.34.5");   Returns 22.34 parsefloat ("0908");   Returns 908 parsefloat ("Blue"); Returns NaN

2. Force type Conversions

You can also use coercion type conversion (type casting) to handle the type of the converted value. You can use coercion type conversions to access a specific value, even if it is of another type.

The 3 mandatory type conversions available in ECMAScript are as follows:

Boolean (value)--Converts a given value to a Boolean;
Number (value)-Converts a given value to a digit (can be an integer or floating point);
string (value)--Converts the given value to a string.

Converting a value with one of these three functions creates a new value that holds the value directly converted from the original value. This can have unintended consequences.

TheBoolean () function returns True when the value to be converted is a string with at least one character, a number other than 0 digits, or an object (which is discussed in the next section). If the value is an empty string, number 0, undefined, or null, it returns FALSE.

You can use the following code snippet to test a Boolean type cast.

JS Code Boolean ("");   False–empty string Boolean ("Hi");   True–non-empty string Boolean (100);   True–non-zero number Boolean (null);   False-null Boolean (0);   False-zero Boolean (new Object ()); True–object

The force type conversion of Number () is similar to the parseint () and parsefloat () methods, except that it converts the entire value, not the partial value.

Remember, the parseint () and parsefloat () methods only convert the string before the first invalid character, so "4.5.6" is converted to "4.5".

Force type conversion with number (), and "4.5.6" returns Nan, because the entire string value cannot be converted to numbers.

If the string value can be completely converted, number () will determine whether to call the parseint () method or call the Parsefloat () method.

The following table describes what happens when you call the number () method on a different value:

Usage Results JS code number (false) 0 number (true) 1 number (undefined) NaN number (null) 0 Number ("5.5") 5.5 number ("a") Number ("5.6.7") NaN number (new Object ()) N An number (100) 100

The last force type conversion method string () is the simplest because it converts any value to a string.

To perform this coercion type conversion, you only need to call the ToString () method of the value passed in as a parameter, that is, convert 1 to "1", convert True to "true", convert false to "false", and so on.

The only difference between casting to a string and invoking the ToString () method is to force a type conversion on a null or undefined value to generate a string without raising an error:

JS Code var s1 = String (null);    "Null" var onull = null;   var s2 = onull.tostring (); Won ' t work, causes an error

3. Using JS variable weak type conversion

For a small example, a look, you will understand.        JS code <script> var str= ' 012.345 ';         var x = str-0;    x = x*1; </script>

The above example uses the characteristics of the weak type of JS, only arithmetic operation, realize the type conversion of string to number, but this method is still not recommended.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: