JS in six types of data (four)--number

Source: Internet
Author: User

The number type should be the most interesting data type in ECMAScript, which uses the IEEE754 format to represent integers and floating point values (floating-point numbers are also known as double-precision values in some languages).    To support various numeric types, ECMA-262 defines different numeric literals.   The most basic numeric literal format is a decimal integer, and a decimal integer can be entered directly into the code as follows: var item = 55; Integers can be represented by octal (base 8) or hexadecimal (base 16) literals, in addition to decimal notation. Where the first digit of the octal literal must be 0 (0), followed by the octal number sequence (0-7). If the value in the literal value is out of range, then the leading 0 is ignored and the subsequent value is parsed as a decimal value.   Take a look at the following example: Var color1=070;   Eight-in-a-year Var color2=079;    Invalid octal value--analytic to the color3=08 var;    Invalid octal value-parsing to 88 literals is not valid in strict mode and causes the JavaScript engine that supports the pattern to throw an error. The first two digits of the hexadecimal literal must be 0x, followed by any hexadecimal digits (0-9 and a-f). Where the literal a-f can be capitalized or lowercase.    As shown in the following example: Var num1=0xa;//16 binary Var num2=0x1f; Hexadecimal 31 in arithmetic calculations, all values in eight hexadecimal and hex are eventually converted to decimal values. 1. Floating-point values    The so-called floating-point value, that is, the number must contain a decimal point, and must have at least one digit after the decimal points. Although there can be no integers before the decimal point, we do not recommend this notation. A few examples of floating-point values:     var floatnum1=1.1;    var floatnum2=0.1;    var floatnum3=.1;  //valid, but not recommended      because the memory space required to save floating-point values is twice times the number of saved values, ECMAScript will lose no chance to convert floating-point values to integer values. Obviously, if the decimal point is not followed by any number, then this value can be saved as an integer value. Similarly, if the floating-point value itself represents an integer (such as 1.0), then the value is also converted to an integer, as shown in the following example:     var floatnum1=1.  //There is no number after the decimal point--resolves to 1    var floatnum2=10.0;    //integer--Parse to 10        for those maxima or minima, a floating-point numeric representation can be represented by e notation (i.e. scientific notation). The value represented by the E notation equals the number in front of e multiplied by the exponential power of 10. The same is true of the format of e notation in ECMAScript, which is preceded by a numeric value (which can be an integer or a floating-point number), an uppercase or lowercase literal e, followed by an exponent in the power of 10, which is used to multiply the preceding number. The following is an example of using the E notation to represent a numeric value:     var floatnum=3.125e7;  //equals 31250000     In this case, the form of the variable floatnum represented by e notation is concise, but its actual value is 31250000. Here, the actual meaning of E notation is " 3.125 Times 10 of seven ".     You can also use e notation to represent very small values, such as 0.00000000000000003, which can be represented by a more concise 3e-17. By default, ECMAScript converts floating-point numbers with 6 or more 0 after the decimal point to an E representationValue (for example, 0.0000003 is converted to 3e-7).     The highest precision for floating-point values is 17 decimal places, but it is far less accurate than integers in arithmetic calculations. For example, the result of 0.1+0.2 is not 0.3, but 0.300000000000000004. This small rounding error can result in the inability to determine a specific floating-point value. For example:     if (a+b = = 0.3) {         //do not do such a test        alert ("You g OT 0.3. ");    }       In this example, we are testing for two numbers and is not equal to 0.3. If these two numbers are 0.05 and 0.25, or 0.15 and 0.15, there will be no problem. As mentioned earlier, if these two numbers are 0.1 and 0.2, then the test will fail. Therefore, never test a particular floating-point value. 2. Range of ValuesDue to memory limitations, ECMAScript cannot save all the values in the world. The minimum value that ECMAScript can represent is saved in Number.min_value--in most browsers, the value is 5e-324; The maximum value that can be represented is saved in Number.max_vlaue--in most browsers, This value is 1.7976931348623157e+328. If a calculation results in a value that exceeds the range of JavaScript values, the value is automatically converted to a special infinity value.    Specifically, if the value is negative, it is converted to-infinity (negative infinity), and if the value is positive, it is converted to Infinity (positive infinity). As mentioned above, if a calculation returns a positive or negative infinity value, the value will not continue to participate in the next calculation because infinity is not able to participate in the calculated value. To determine whether a value is poor (in other words, between the minimum and maximum values), you can use the Isfinite () function.    This function returns True when the parameter is between the minimum and maximum values, as shown in the following example: Var result=number.max_value + number.max_value; Alert (isfinite (result)); False Although it is rare to have some values outside the representation range in calculations, it is also necessary to monitor these values when performing calculations of very small or large numbers. 3.NaN    NaN, non-numeric (not a number) is a special value that represents a case in which an operand that originally returned a numeric value did not return a value (so that no error is thrown). For example, in other programming languages, dividing any number by 0 will result in an error, thereby stopping code execution. In ECMAScript, however, any number divided by 0 returns Nan, so it does not affect the execution of other code. The     Nan itself has two unusual features. First, any operation involving Nan, such as NAN/10, will return Nan, a feature that can cause problems in multiple computations. Second, Nan is not equal to any value, including the Nan itself. For example, the following code returns false:     Alert (nan = = Nan);//false     for these two characteristics of Nan, ECMAScript defines the isNaN () function. This function takes a parameter, which can be any type, and the function will help us determine whether the parameter is "not a value". IsNaN () after receiving a value, it attempts to convert the value to a number. Some values that are not numeric are converted directly to numeric values, such as the string "10" or the "Boolean" value. Any value that cannot be converted to a number will cause the function to return true. Take a look at the following example:     alert (IsNaN (NaN)); true    alert (IsNaN (10));  //false (10 is a numeric value)     alert (IsNaN ("10"));  //false (can be converted to a value of ten)     alert (IsNaN ("Blue"));  //true (cannot be converted to numeric value)     alert (IsNaN (true));  //false (can be converted to a value of 1)      This example tests 5 different values. The first value of the test is Nan itself, and the result will of course return true. The value 10 and the string "10" were tested separately, and the two Tests returned false because the former itself was a value, while the latter could be converted to a value. But the string "blue" cannot be converted to a numeric value, so the function returns True. Because a Boolean value of true can be converted to a number 1, so the function returns FALSE. 4. Numeric ConversionsThere are 3 functions that can convert non-numeric values to numeric values: Number (), parseint (), and parsefloat (). The first function, the transformation function number (), can be used for any data type, while the other two functions are specifically used to convert a string into a numeric value.    The 3 elder functions will return different results for the same input. The conversion rules for the number () function are as follows.
    1. If it is a Boolean value, True and false are converted to 1 and 0, respectively.
    2. If it is a numeric value, it is simply passed in and returned.
    3. If it is a null value, 0 is returned.
    4. If it is undefined, return nan.
    5. If it is a string, follow these rules:
     a. If the string contains only numbers (including cases preceded by a plus or minus sign), it is converted to a decimal value, that is, "1" becomes 1, "123" becomes 123, and "011" becomes 11 (note: Leading 0 is ignored)         b. If the string contains a valid floating-point format, such as "1.1", it is converted to the corresponding floating-point value (also ignored by the leading 0);      C. If the string contains a valid hexadecimal format, for example: "0xf", convert it to decimal integer value of the same size;     d. If the string is empty (contains no characters), convert it to 0;     e. If the string contains characters other than the above format, it is converted to Nan.    6. If it is an object, call the object's valueof () method, and then transform the returned value according to the previous rule. If the result of the conversion is Nan, the object's ToString () method is called, and then the returned string value is converted again according to the previous rule.     using number () to convert various data types to numbers based on so many rules is really a bit complicated. Here are a few specific examples.      var num1=number ("Hello world!");  //NaN    var num2=number ("");              //0    var num3=number ("000011");        //11    var num4=number (true);            //1      First, the string "Hello world! "is converted to Nan because it does not contain any meaningful numeric values. The empty string is converted to 0. The string "000011" is converted to 11 because it ignores the leading 0. Finally, the value of true is converted to 1.     because the number () function is more complex and not enough to convert a stringReasonable, so the parseint () function is more commonly used when working with integers. The parseint () function converts a string more to see whether it conforms to a numeric pattern. It ignores the spaces in front of the string until the first non-whitespace character is found. If the first character is not a numeric character or minus sign, parseint () returns Nan, that is, converting an empty string with parseint () returns Nan (number () returns 0 for an empty string). If the first character is a numeric character, parseint () continues to parse the second character until all subsequent characters have been parsed or a non-numeric character is encountered. For example, "123blue" is converted to 1234 because "blue" is completely ignored. Similarly, "22.5" is converted to 22 because the decimal point is not a valid numeric character.     If the first character in a string is a numeric character, parseint () can also recognize various integer formats (decimal, octal, and hexadecimal discussed earlier). That is, if the string starts with "0x" and is followed by a numeric character, it is treated as a hexadecimal integer, and if the string starts with "0" followed by a numeric character, it is parsed as an octal number.     To better understand the conversion rules for the parseint () function, here are some examples:     var num1=parseint ("1234blue");  //1234    var Num1=parseint ("");   //nan    var num1=parseInt (" 0xA ")    //10 (hex number)     var num1=parseint (" 22.5 ");   //22    var num1=parseint ("070"),    //56 (octal number)     var num1=parseint ("70");    //70 (decimal)     var num1=parseint ("0xf");    //15 (hexadecimal number)     &nbsp When parsing strings like octal literals using parseint (), there are differences between ECMASCRIPT3 and 5. For example:    //ecmascript 3 is considered 56 (octal), ECMAScript 5 is considered 70 (decimal)     var num=parseint ("070");      in ECMAScript 3 JavaScript engine, "070" is treated as octal literal, so the converted value is 56 decimal. And in ECMAScript 5 JavaScript engine, parseint () No longer has the ability to parse octal values, so a leading 0 is considered invalid, thus treating the value as "70", resulting in a decimal 70. In ECMAScript 5, this is true even in non-strict mode.     To eliminate the confusion that can be caused by using the parseint () function, you can use the second parameter of the function: the technique used when converting (that is, how many binary). If you know that the value to parse is a string in hexadecimal format, specifying cardinality 16 as the second parameter guarantees the correct results, such as:     var num=parseint ("0xAF", 16);    //175     In fact, if you specify 16 as the second argument, the string can be without the preceding "0x" as shown below:     var num1=parseint (" AF ", 16); 175    var num2=parseint ("AF");    //NaN     The first conversion in this example was successful, and the second one failed. The difference is that the first transformation passes in the cardinality, explicitly telling parseint () to parse a hexadecimal-formatted string; the second conversion finds that the first character is not a numeric character and therefore terminates automatically.      var num1=parseint ("10", 2);    //2 (by binary parsing)     var num2=parseint ("10", 8);    //8 (parsing by octal)     var num3=parseint ("10", 10);    //10 (resolution by decimal)     var num4=parseint ("10", 16);    //16 (parse in hexadecimal)      Do not specify cardinality means let parseint () decide how to parse the input string, so in order to avoid error parsing, we recommend explicitly specifying the cardinality regardless of the circumstances.     Similar to the parseint () function, parsefloat () also parses each character starting with the first character (position 0). It is also parsed until the end of the string, or until an invalid floating-point numeric character is encountered. That is, each decimal point in the string is valid, and the second decimal point is invalid, so the string following it is ignored. For example, "22.34.5" will be converted to 22.34.     The second difference between parsefloat () and parseint (), except that the first decimal point is valid, is that it always ignores the leading 0. parseint () can recognize all floating-point numeric formats discussed previously, and also include decimal integer formats. But the hexadecimal-formatted string is always converted to 0. Because Parsefloat () parses only the decimal value, it does not specify the usage of the cardinality with the second argument. Finally, note that if the string contains a number that can be resolved to an integer (no decimal point, or 0 after the decimal point), parsefloat () returns an integer. Here are a few typical examples of using parsefloat () to convert numeric values.      var num1  =  parsefloat ("1234blue");  //1234 (integer)     var num2  =  parsefloat ("0xA");  //0    var num3  =  parsefloat ("22.5");  //22.5    var num4  =  parsefloat ("22.34.5");  //22.34    var num5  =  parsefloat ("0908.5);  //908.5    var num6  =  parsefloat ("3.125e7");  //3125000        welcome attention to the public number: Wcs290130--javascript those things. JavaScript Technology Exchange Group:344292264 .

JS six data types (four)--number (EXT)

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.