JavaScript string to Value

Source: Internet
Author: User
Tags type casting

JavaScript string to value: There are three main ways

Conversion function, coercion type conversion, using JS variable weak type conversion.

1. Conversion functions

JS provides two conversion functions for parseint () and parsefloat (). The former converts the value into an integer, which converts the value into a floating-point number. Only these methods are called on the string type, and the two functions function correctly, and all other types return Nan (not a number).

parseint () and parsefloat () will parse the string carefully before judging whether the string is a numeric value. The parseint () method first looks at the character at position 0, determines if it is a valid number, and if not, the method returns Nan, and no further action is taken. However, if the character is a valid number, the method will look at the character at position 1 and perform the same test. This process continues until a character is found that is not a valid number, at which point the 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 () returns 1234 because when it detects the character B, it stops the detection process. The numeric literals contained in the string are correctly converted to numbers, so the string "0xA" is correctly converted to the number 10. However, the string "22.5" is converted to 22 because the decimal point is an invalid character for integers. Some examples are as follows:

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

The

parseint () method also has a base mode, which converts binary, octal, hexadecimal, or any other string into integers. The base is specified by the second parameter of the parseint () method, so to parse the hexadecimal value, call the parseint () method as follows: parseint ("AF",  );  //returns    175 Of course, for binary, octal, or even decimal (the default mode), you can call the parseint () method: parseint ("ten",   2);  //returns    2 parseint ("Ten",   8);  //returns   8 parseint ("Ten",   10);   //returns   10 If the decimal number contains a leading 0, it is best to use cardinality 10 so that the octal value is not accidentally obtained. Example: parseint ("010");  //returns   8 parseint ("010",   8);  //returns    8 parseint ("010",  );  //returns   10 In this code, two lines of code parse the string "010" into a number. The first line of code considers this string as an octal value, and parses it in the same way as the second line of code (the declaration base is 8). The last line of code declares that the cardinality is 10, so iNum3 finally equals 10.

The Parsefloat () method is similar to the parseint () method, viewing each character starting at position 0 until the first non-valid 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 there are two decimal points, the second decimal point is 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 the leading 0, so the octal number 0908 is parsed to 908. For hexadecimal 0xA, the method returns Nan because, in a floating-point number, X is not a valid character. In addition, parsefloat () has no base mode.

The following is an example of using the Parsefloat () method: 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. Forcing type conversions

You can also use the coercion type conversion (type casting) to handle the type of the converted value. A specific value can be accessed using a coercion type conversion, even if it is of a different type. The 3 coercion type conversions available in ECMAScript are as follows: Boolean (value)-converts the given value to a Boolean type, number (value)-converts the given value to a digit (which can be an integer or a floating point); String (value)-- Converts the given value to a string. Using one of these three functions to convert the value, a new value is created that holds the value converted directly from the original value. This can cause unintended consequences. The Boolean () function returns True when the value to be converted is a string of at least one character, a non-0 number, or an object (this is discussed in the next section). If the value is an empty string, the number 0, undefined, or null, it returns FALSE.

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

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 coercion type conversion of number () is similar to the parseint () and parsefloat () methods, except that it transforms 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". Coercion type conversion with number (), "4.5.6" returns Nan because the entire string value cannot be converted to numbers. If the string value can be fully 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 different values:

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

The last method of forcing a type conversion 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 that passes in the value 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 calling the ToString () method is that coercion of type conversions on null or undefined values can generate strings without throwing an error:

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

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

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

JavaScript string to Value

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.