Deep understanding of number types in JS

Source: Internet
Author: User
Tags mathematical constants mathematical functions sin

Learn more about number types

Number type, as one of the basic data types of JS, is applied in various scenarios in the program, and its importance is like numbers for our daily life.

Below let us come together in-depth understanding under, for later "Riding Pentium" good foreshadowing.

How to define

In general, we can define a number directly using the numeric literal format, as follows:

var num1 = 15;var num2 = 7;console.log(typeof num1); // numberconsole.log(typeof num2); // number
Numeric type

The defined values can be divided into two types, integer and floating-point numbers, respectively.

Integer

integers, which can be represented by decimal, octal, hexadecimal literals. (default is 10 in value)

Decimalvar intNum1 =35}Positivevar intNum2 =0;0var intNum3 =-3;Negative//octal //the first bit must be 0, the remainder of the value range is 0-7// Invalid octal will ignore the preceding 0 directly, parsing to decimal var octalNum1 = 070; //octal (7*8 + 0) var octalNum2 = 079; //Invalid octal number, 9 exceeds 8 decimal range, resolves to 79var octalNum3 = 08 ; //invalid octal number, direct parse pseudo 8//hex // The first two bits must be 0x, the rest of the value range is 0~9 or A~fvar hexNum1 = 0XA; //16 binary 10var hexNum2 = 0x1f; //16 binary (1*16 +)            

In arithmetic calculations, all values in eight hexadecimal and hex are eventually converted to decimal values.

// 对前面定义的八进制和十六进制数值进行运算console.log(octalNum1 + hexNum1); // 66
Floating point number

Floating point numbers are actually the decimals we usually call, so there must be a decimal point. A simple example is as follows:

var floatNum1 = 5.2;var floatNum2 = 3.14;

Floating-point numbers occupy twice times as much memory space as integers. If there is only 0 or no number after the decimal point, in order to save memory space, the decimal will be converted to an integer, as follows:

var floatNum3 = 5.0; // 5var floatNum4 = 2.; // 2

In arithmetic operations, floating-point numbers are not as accurate as integers, so it is generally not necessary to use floating-point numbers for calculations, as follows:

var floatNum4 = 0.1; var floatNum5 = 0.2; // 0.1 + 0.2 不等于 0.3console.log(floatNum4 + floatNum5); // 0.30000000000000004

An e notation is generally used for extremely small floating-point numbers, as follows:

var floatNum6 = 3.2e7;// 3.2×10(7次幂) var floatNum7 = 3.2e-7;// 3.2×10(-7次幂)
NaN

NaN is a shorthand for not a number, that is, non-numeric. It is a special value that is used to represent an operand that would otherwise return a numeric value, and the result does not return a numeric value.

NaN has two unusual features:

    • Any operation that involves Nan will return Nan
    • The NaN value is not equal to any value, including itself.
console.log(NaN / 10); // NaNconsole.log(NaN == NaN); // false

For these two features, JS provides a isNaN() function. The function takes a parameter (which can be any type), and the function helps us determine whether the parameter is "not a value".

Note: The arguments passed will involve the problem of numeric conversions, such as "10" the string can be converted to 10, but the "blue" string cannot be converted to a number, soisNaN(‘blue‘) == true

console.log(isNaN(NaN)); // trueconsole.log(isNaN(10)); // falseconsole.log(isNaN("10")); // false,可以被转成数值 10console.log(isNaN("blue")); // trueconsole.log(isNaN(true)); // false,可以被转成数值 1
numeric conversions

There are three functions that can convert a non-numeric value to a value: Number() , parseInt() parseFloat() . The first one can be used for any data type, and the latter two are dedicated to converting a string to a numeric value.

A simple example is as follows:

Number ()Conversion rules are more complex, you can refer to the following informationvar numN1 =Number ("Hello world!");NaNvar numN2 =Number (" ");0 empty string converted to 0var numN3 =Number ("000011");11var numN4 =Number (true);1parseintIgnore decimal pointString will be converted to numeric valuevar numI1 =parseint (22.5);22var numI2 =parseint ("1234blue");1234var numI3 =parseint (" ") ;NaNvar numI4 =parseint ("70");70 (decimal number)var numI5 =parseint ("070");56 (octal number)var numI6 =parseint ("0xA");10 (hexadecimal number)ParsefloatString will be converted to numeric valueIf there are multiple decimal points, only the first one is taken, and all the rest is discardedvar numF1 =Parsefloat ( "1234blue"); //1234 (integer) var numF2 =  parsefloat ( "0xA"); //0var numF3 = parseFloat ( "22.5"); //22.5var numF4 = parseFloat ( Span class= "hljs-string" > "22.34.5"); //22.34var numF5 = parseFloat ( Span class= "hljs-string" > "0908.5"); //908.5var numF6 = parseFloat ( Span class= "hljs-string" > "3.125e7"); //31250000            

For more information, refer to:

    • JavaScript numeric conversions (non-numeric conversions to numeric values)
    • parseint
    • Parsefloat
Range of values

Due to memory limitations, JS cannot save all values. So what is the maximum minimum value it can represent? We can use the and property representation of the number object MIN_VALUE MAX_VALUE (rarely used, probably know it, and can be consulted when it's really needed):

    • Number.MIN_VALUEThe smallest positive number that can be represented is the positive value that is closest to 0 (it does not actually become 0), and it has an approximation of 5 x 10-324.
    • Number.MAX_VALUEAs the maximum positive number that can be represented, it has an approximate value of 1.7976931348623157 x 10308

If a value exceeds the maximum representation of a number, it automatically becomes a Infinity value (infinite number), and we can use the isFinite() number object to determine whether one is a finite number, or an infinite number if the non-finite number.

console.log(Number.isFinite(56)); // trueconsole.log(Number.isFinite(Number.MAX_VALUE + Number.MAX_VALUE)); // false

More properties and methods for number objects can be consulted: MDN

Mathematical functions

Remember, when we went to school, we learned a lot of mathematical formulas to deal with numbers, ah, what should be done in JS?

Don't panic, JS has built in a math object that has the properties and methods of mathematical constants and functions.

Let's start with a few simple examples:

The function returns the nearest integer value after rounding a number.Math.Round (3.4);//3//function returns a random floating-point number, in the range [0,1] //random floating-point numbers, each time not the same //function returns a number of square roots  MATH.SQRT (9); //3//function returns the maximum value in a given set of numbers 10, 20, 13, 18); //20//sin method returns a numeric value from 1 to 1 that represents the sine of a given angle (in radians). //Math.PI represents pi, the ratio of circumference and diameter of a circle, approximately equal to 3.14159. math.sin (math.pi/2); //1             

More math objects are available for reference: Math Object | MDN

Deep understanding of number types in JS

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.