We are all too familiar with numbers. Let num = 123; You can create a number.
Number(thing) converts any type of data to a Number.
New Number(thing) allows you to convert any type of data into an object of type Number.
Numeric direct quantities can directly use properties and methods on the Number object, such as 100[‘toFixed’](1). Internally, the language temporarily encapsulates 100 as an object and executes the corresponding method. You can view it as Number(100).tofixed (1).
Direct numerical quantities can also be operated on dots (.) Use properties and methods on the Number object, but with Spaces after the Number, such as 100. toFixed(1), because the compiler does not know. Represents a decimal point or an operator. Must be whitespace. It’s preceded by a complete number.
In addition to the usual numbers, NaN and Infinity are of type Number. In addition to decimal, JavaScript supports binary (0b111), octal (0o777), hexadecimal (0xfff), and scientific notation (2.345e+3).
Static attributes
These static attributes are rarely used and are generally used to detect whether precision is exceeded. (Accuracy is mentioned at the end of the article)
- EPSILON: The minimum interval between two representable numbers. 2-52.
- MAX_SAFE_INTEGER: indicates the maximum safe integer. 253-1.
- MIN_SAFE_INTEGER: indicates the minimum safe integer. – 2-53 + 1.
- MAX_VALUE: indicates the maximum positive number that can be expressed. 21023 * (253-1) / 252.
- MIN_VALUE: the smallest positive number that can be represented, that is, the nearest positive number to 0. 2-1022 * (1/252) = 2-1074.
- NaN: Special “non-numeric” value.
- POSITIVE_INFINITY: Special positive infinity value that returns the change on overflow. The overflow positive numbers are all of this value.
- NEGATIVE_INFINITY: Special negative infinity value that is returned when overflow occurs. The negative overflow value is this value.
Just to be clear, safe integers are integers that do the right calculation. When adding integers, you need to convert the digit digits to the same value, for example, 252+1 = 252+252*2-52, and then add and subtract the fractional digits. When the safe range is exceeded, such as 253+1, it is found that 1 cannot be converted to 253*2-53 because the fractional bit has only 52 digits.
MAX_SAFE_INTEGER + 1 and number.min_safe_INTEger-1 can be calculated correctly.
A static method
The first and last two methods are more commonly used. Number. IsNaN (value) is useful because we cannot determine whether a value is a NaN by value===NaN.
- isNaN(value):judge
value
Whether it isNaN
. - IsFinite (value) : judgment
value
Returns whether it is a finite number, non-numeric typefalse
. - IsInteger (value) : judgment
value
If the value is an integer, the value is returned for non-numeric typesfalse
. - IsSafeInteger (value) : judgment
value
Whether the value is a safe integer (-(2)531) to 253Between -1). - parseFloat(string): Takes a stringParse to a floating point number. Incoming values return the original value; Non-strings and numbers are returned
NaN
; For other cases, please refer to the documentation. - parseInt(string[, radix]): Puts a string based on the given base numberParse into integers.
radix
The default value is 10, that is, decimal. Passing non-strings and numbers returnsNaN
; For other cases, please refer to the documentation.
Instance methods
- toExponential(fractionDigits?) : Returns aIn the form of powers (scientific notation)
Number
Object string.fractionDigits
The default value after the decimal point will be represented by the largest number of digits possible. Example:100 .toExponential(); // "1e+2"
,2.345. ToExponential (2); 2.35 e+0 "/ /"
. - toFixed(digits?): Returns the string form of the fixed-point representation of the given value, i.ekeep
digits
Decimal places.digits
The default is 0. Commonly used to reduce the longitude of a decimal point, e.g2.345. ToFixed (2); / / "2.35"
. - ToLocaleString ([locales [, options]]) : Returns the locale-specific representation of this number.
- toPrecision(precision?)Returns theRepresented in fixed point or exponential notationThe string of a numeric object.
precision
An integer representing the number of valid numbers. If omitted, the original value is returned. Example:100 .toPrecision(2); 1.0 e+2 "/ /"
,2.345. ToPrecision (3); / / "2.35"
. - toString(radix?) : returns the specified value
Number
The string representation of an object. Radix denotes the base of the conversion (from 2 to 36), which defaults to 10. - ValueOf () : Returns a by
Number
The original value wrapped by the object.
The Math object
Unlike other global objects, Math is not a constructor. All properties and methods of Math are static. The constant PI you use can be represented by math.pi, and math.sin (x) calls the sin function with x as the argument. Constants in JavaScript are defined as real numbers with full precision.
attribute
It’s used to get mathematical constants.
- E: Euler’s constant, also the base of the natural logarithm, is approximately 2.718.
- The natural log of log 2:2 is approximately 0.693.
- Log 10: the natural log of 10, approximately 2.303.
- LOG2E: Log base 2 of E, approximately equal to 1.443.
- LOG10E: log base 10 of E, approximately equal to 0.434.
- PI: the value of PI is approximately 3.14159.
- SQRT1_2: square root of 1/2, approximately equal to 0.707.
- SQRT2: square root of 2, approximately equal to 1.414.
methods
Ordinary operations:
- Abs (x) : Returns the absolute value of x.
- Sign (x) : returns xsymbolFunction, which can return 5 possible values: the argument is ±0, which returns the original value; Other positive numbers are returned
1
; Other negative numbers return- 1
; Other parameters returnNaN
. - Ceil (x) : returns the rounded value of x.
- Floor (x) : returns the rounded down value of x.
- Round (x) : Returns a rounded integer.
- Trunc (x) : Returns the integer part of x, minus the decimal.
- Random () : Returns a pseudo-random number between 0 and 1.
Root:
- SQRT (x) : Returns the square root of x.
- hypot(… [x1,x2,…] ?). : returns the square root of the sum of squares of all its arguments.
- CBRT (x) : Returns the cube root of x.
Power operation:
- Exp (x) : returns Ex, where E is Euler’s constant.
- Expm1 (x) : returns the value exp(x) -1.
- Pow (x, y) : returnsX to the y. Here’s another way to write it, using the ** operator, i.e
x**y
.
Logarithmic operation:
- Log (x) : Returns the natural log of x.logeX, namely lnX.
- Log1p (x) : Returns the natural log of x+1, equivalent to
Math.log(x+1)
. - Log10 (x) : Returns the log base 10 of x.log10XThat lgX.
- Log2 (x) : Returns the log base 2 of x.log2X.
Trigonometric functions:
- Sin (x) : Returns the sine of x.
- Cosine (x) : Returns the cosine of x.
- Tan (x) : Returns the tangent of x.
- Asin (x) : Returns the arcsine of x.
- Acos (x) : Returns the inverse cosine of x.
- Atan (x) : Returns the arctangent of x between -pi /2 and PI/2 radians.
- Sinh (x) : Returns the hyperbolic sine of x.
- Cosh (x) : Returns the hyperbolic cosine of x.
- Tanh (x) : Returns the hyperbolic tangent of x.
- Asinh (x) : Returns the inverse hyperbolic sine of x.
- Acosh (x) : Returns the inverse hyperbolic cosine of x.
- Atanh (x) : Returns the inverse hyperbolic tangent of x.
- Atan2 (y, x) : Returns the arctangent of y/x.
Get the most value:
- max(… [x1, x2,… ?). : Returns the maximum value of all parameters.
- min(… [x1, x2,… ?). : Returns the minimum of all parameters.
Accuracy:
- Clz32 (x) : Returns the number of binary leading zeros of x converted to a 32-bit unsigned integer.
- Fround (x) : Returns the closest single-precision floating-point representation of the number x.
- Imul (x1, x2) : The result of the c-like 32-bit integer multiplication operation of two parameters. (That is, if the absolute value of the calculation result is less than 231-1, the correct result can be obtained)
Precision problem
0.1 + 0.2! = = 0.3
For accuracy, start with a simple addition.
console.log(0.1 + 0.2); / / 0.30000000000000004Copy the code
This is because JavaScript adopts the IEEE 754 standard, so the above problems are not unique to JavaScript, but are common in programming languages that use this standard. The following is a brief explanation of why the problem occurs. (Please refer to books or documents for relevant professional knowledge)
The composition of floating point numbers
IEEE 754 provides for single precision (32 bits), double precision (64 bits), extended single precision (43 bits above, rarely used), and extended double precision (79 bits above, usually implemented as 80 bits). JavaScript uses double precision. A floating point number (value) can be represented like this:
A floating point number is stored as follows:
It is divided into three parts:
- The sign bit(sign), only 1 bit, 0 represents
+
And 1 for-
. - Index a(Exponent), 8 bits for single precision; Double precision accounts for 11 bits. And notice, this part right here isThe index of 2. The value of the exponent bit is the true exponent value plusExponential offset. For example, for single precision, the exponential bits store 2 and add 27Minus 1, which is 131, is written in binary
1000, 0011,
. The range of exponential bits is described below. - A fraction is the number of digits left. The following describes the conversion of binary fractional bits.
A floating-point number in protocol form
If the encoded value of the exponent part of a floating-point number is between 0 < exponent≤ 2E-2, and the highest significant bit (i.e. integer number) of the fraction part is 1 (which is not stored) in scientific notation, then the floating-point number is said to be in specification form. In short, the exponent is 000 in binary… Between 001 and 111… 110; The actual value of the fraction is greater than or equal to 0.5 and less than 1. For conversion, it will be said below.
A floating point number in unspecified form
If the encoded value of the exponent part of the floating-point number is 0, the actual exponent value is -126; If the fraction part is non-zero, the float is called a non-canonical float. The IEEE 754 standard states that the exponential offset of a non-specified floating-point number is 1 less than that of a specified floating-point number, that is, 2E-1-2. It is mainly used to solve the distance between minimum specification number and zero in the sense of filling absolute value.
Exponential offset
(E denotes the number of exponential bits below)
For floating-point numbers in specification form, the exponential offset is 2E-1-1. Since this value cannot be 0, the actual exponents range from -126 to 127.
For unregulated floating-point numbers, the exponential offset is 2E-1-2, that is, 1 less than the offset of the regulated floating-point numbers. Since this value can only be 0, the actual index value is -126.
In general, the actual index values range from -126 to 127. 000… 001 is the minimum exponent bit of a floating-point number in specification form; 000… 000 is the minimum exponent bit for a non-canonical floating-point number, and both represent an actual exponent value of -126.
Special values
indexIt’s 0 and mantissa
The decimal partIt’s 0, this number plus or minus 0.
index = 2
e-1Minus one and mantissa
The decimal partIt’s 0. This number is plus or minus
up(also related to sign bits)
index = 2
e-1Minus one and mantissa
The decimal partNon-0, this number is represented as not a number (NaN).
Fractional bit conversion
The decimal value of a fraction must be greater than 1 and less than 2. The following to
1.625
As an example.
We can’t just see 1625 converted to binary. You need to use the following method (f for the current decimal value) :
So the first step is to subtract 1 from this number to get the new number. The new value *2 is 1 if the integer part is 1, and 0 otherwise; Then continue to take the decimal part of the same operation, get the value of the following bits, until the number is exactly 0 or reaches the maximum number of specified digits (maximum accuracy).
As a practical example, for 1.625:
- The initial value
1.625
, the integer bit is 1, then the first digit is 1, and the operation continues with 0.625. 0.625 * 2 = 1.250
If the integer bit is 1, the second digit is 1 and the operation continues with 0.25.0.25 * 2 = 0.5
, the integer bit is 0, then the third bit is 0 and the operation continues with 0.5.0.5 * 2 = 1.0
, the integer bit is 1, then the fourth bit is 1, after the decimal point is 0, the conversion is finished;
We can complete the digits with 0.
So, in binary, the first significant digit has to be 1, so that 1 is not stored. How do you go from binary worth to decimal worth? For the above example: “1101”/23=13/8=1.625)
Formatted float
Floating-point numbers greater than 1 or less than 0.5 need to be formatted to see what the values of the “three parts” are. 1≤fraction<2.
For example, 6.625 needs to be converted to 1.65625 * 22. Then we use the above method to convert 1.65625 into binary to 110101 00… .
However, the highest 1 bit is not stored, so the resulting binary value of the fractional bit is 10101 00… (Mantissa is completed with 0).
The exponent bit is 3, plus the offset to the binary value of 100… 011.
Fraction ≥2 is multiplied by 2n (n>0). The fraction less than 1 is equal to 2n, except that n is less than 0.
More intuitive conversion method
6.625
For example:
- Put the decimal forward and backwardDivided into twoLet’s see
6
and0.625
. - We have toThe integer part
6
Is familiar with the base conversion, the result is110
. - whileAfter the decimal point
0.625
Following a conversion rule similar to the fractional bits above, but ignoring the first step, the result is101
. - The combination of the two
110.101
. - Converted to
1.xxxx
Is of the form, i.e1.10101
, the highest bit is omitted, getScore afor10101
. - Compared to the original value
110.101
If the decimal point of is moved 2 places to the left, thenIndex aThe value of 2 plus the exponential offset is worth to100... 001
(0 is omitted). - Finally combine into
0 100... 001 101010...
(0 is omitted).
For numbers less than 1, such as 0.2, the same is done, except that in step 6, “move to the left” becomes “move to the right”, resulting in a negative exponent value of -3, plus the exponent offset worth 011… 100.
Back to the question
So for both 0.1 and 0.2, the binary values given by the above method are 11001100… “Are repeated with 1100.
The number of digits a computer can store is finite, and the excess digits must be rounded off. So for this kind of thing, which cannot be fully represented in finite precision, it will cause a loss of precision. Is 11001100… Conversion from binary back to decimal is always a bit smaller than the original value.