preface
This chapter describes numerical extensions. Many new methods are added, some of which are not commonly used.
Link to the original text of this chapter: Numerical extension
Binary representation
ES6 provides a new way to write binary and octal values, which are represented by prefixes 0b (or 0b) and 0o (or 0o) respectively.
Octal is no longer allowed to be represented by the prefix 0.
To convert string values prefixed with 0b and 0o to decimal, use the Number method.
console.log(Number('0b10')); // Binary 2 console.log(Number('0o10')); // Octal 8
Numeric separator
ES2021 allows JavaScript values to use underscores () as separators.
The value separator is mainly used to increase the readability of values when writing values, not to process external input data. It has no impact on the storage and output of JavaScript internal values.
be careful:
- It cannot be placed in the leading or trailing of the value.
- Two or more separators cannot be joined together.
- There must be no separator before or after the decimal point.
- In scientific counting, there can be no separator before and after e or e representing the index.
- The delimiter cannot be followed by a hexadecimal prefix
- Some methods of converting a string to a numeric value do not support numeric separators
Numeric separators can also be used for other hexadecimals
const sample10 = 1000_1000_1000; const sample2 = 0b1000_1000; const sample8 = 0o1000_1000; console.log(sample10); // Decimal 10001000 console.log(sample2); // Binary 136 console.log(sample8); // Octal 2097664
Note: Number(), parseInt(), parseFloat() do not support number separators
Numerical method
Number.isFinite(), Number.isNaN()
ES6 provides two new methods: Number. Isfinish () and Number.isNaN() on the Number object.
- Number. Isfinish() is used to check whether a value is finite, that is, it is not infinite.
- Number.isNaN() is used to check whether a value is NaN.
be careful:
How are the two new methods different from the previous global methods isfinish and isNaN?
- These two new methods are only valid for numerical values,
- The traditional method first calls Number() to convert a non numeric value into a numeric value, and then makes a judgment,
isFinite(25) // true isFinite("25") // true Number.isFinite(25) // true Number.isFinite("25") // false Number.isFinite(Infinity); // false Number.isFinite(-Infinity); // false isNaN(NaN) // true isNaN("NaN") // true Number.isNaN(NaN) // true Number.isNaN("NaN") // false
Number.parseInt(), Number.parseFloat()
ES6 transplants the global methods parseInt() and parseFloat() to the Number object, and the behavior remains completely unchanged. It is mainly used for modularization of global variables
- The parseInt() function parses a string and returns an integer.
- The parseFloat() function parses a string and returns a floating point number.
// Global method of ES5 const sampleInt = parseInt('11.11'); const sampleFloat = parseFloat('1a2b3c'); // Number method of ES6 const sampleInt1 = Number.parseInt('11.11'); const sampleFloat1 = Number.parseFloat('1a2b3c'); console.log(sampleInt, sampleFloat); // 11, 1 console.log(sampleInt1, sampleFloat1); // 11, 1
Number.isInteger()
The Number.isInteger() method is used to determine whether a given parameter is an integer.
be careful:
- Since integers and floating-point numbers use the same storage method, 4 and 4.0 are considered the same value. All are integers
- The parameter needs to be a numeric value. The parameter is not a numeric value. Number.isInteger() directly returns false.
- Since the JavaScript numerical accuracy can reach 53 binary bits at most, if the numerical accuracy exceeds this limit, the 54th and subsequent bits will be discarded, which may lead to misjudgment of Number.isInteger. The same is true for absolute values.
const sample1 = Number.isInteger(44); const sample2 = Number.isInteger(44.00); // Equivalent to 44 const sample3 = Number.isInteger('44'); // Non numeric value directly returns false const sample4 = Number.isInteger(44.0000000000000000987654321); // Misjudged as true console.log(sample1, sample2, sample3, sample4); // true, true, false, true
Numeric new constant
Number.EPSILON
ES6 adds a tiny constant Number.EPSILON on the Number object. It represents the difference between 1 and the smallest floating-point Number greater than 1.
For 64 bit floating-point numbers, the minimum floating-point number greater than 1 is equivalent to binary 1.00.. 001 (51 consecutive zeros after the decimal point). After subtracting 1, this value is equal to the - 52nd power of 2.
Number.EPSILON is actually the smallest precision that JavaScript can represent.
Number.EPSILON is essentially an acceptable minimum error range.
const sample = Number.EPSILON === Math.pow(2, -52); console.log(sample); // const sample1 = Number.EPSILON; console.log(sample1); // const sample2 = Number.EPSILON.toFixed(20); console.log(sample2); //
Security integer and Number.isSafeInteger()
The range of integers that JavaScript can accurately represent is between - 2 ^ 53 and 2 ^ 53 (excluding two endpoints). Beyond this range, this value cannot be accurately represented.
ES6 introduces Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER these two constants are used to represent the upper and lower limits of - 2 ^ 53 to 2 ^ 53.
const sample = Number.MAX_SAFE_INTEGER === 9007199254740991; const sample1 = Number.MIN_SAFE_INTEGER === -Number.MAX_SAFE_INTEGER; const sample2 = Number.MIN_SAFE_INTEGER === -9007199254740991; console.log(sample,sample1,sample2);
Number.isSafeInteger() is used to determine whether an integer falls within this range. For non integers, false is returned
const sample = Number.isSafeInteger(44); // integer const sample1 =Number.isSafeInteger(44.001); // Non integer const sample3 =Number.isSafeInteger(9007199254740990); const sample3 =Number.isSafeInteger(9007199254740992); console.log(sample,sample1,sample2,sample3); // true, false, true, false
Extension of Math object
ES6 adds 17 Math related methods to Math objects.
All of these methods are static and can only be called on Math objects.
- Math.trunc() - rounding.
- Math.sign() - judge whether a number is positive, negative, or zero.
- Math.cbrt() - calculates the cube root of a number
- Math.clz32() - calculates the number of leading zeros in the 32-bit binary form of a number.
- Math.imul() - computes 32-bit multiplication of class C for two parameters.
- Math. Forward() - returns the 32-bit single precision floating-point number form of a number.
- Math.hypot() - returns the square root of the sum of squares of all parameters.
- Math.expm1() - returns ex - 1, where x is a parameter
- Math.log1p() - returns the natural logarithm after the parameter + 1
- Math.log10() - returns the base 10 logarithm of the parameter
- Math.log2() - returns the base 2 logarithm of the parameter
- Math.sinh() - the function returns the hyperbolic sine of a number in angle.
- Math.cosh() - function returns the hyperbolic cosine function of a numeric value.
- Math.tanh() - the function returns the hyperbolic tangent of a number.
- Math.asinh() - the function returns the inverse hyperbolic sine of a given number.
- Math.acosh() - returns the inverse hyperbolic cosine of a number.
- Math.atanh() - the function returns a numeric inverse hyperbolic tangent.
Math.trunc()
The Math.trunc() method removes the decimal part of the number and only retains the integer part. It is a rounding operation.
There are three methods in Math: Math.floor(), Math.ceil(), Math.round(), which are also used for rounding operations.
- Math.floor() rounded down;
- Math.ceil() rounded up;
- Math.round() performs the rounding operation.
- Math.trunc() removes the decimal part and retains only the integer part.
const sample = Math.trunc(4.9); // Remove decimal places and keep whole numbers const sample1 = Math.trunc('4.4'); // For other data types, first call Number to convert to numeric type const sample2 = Math.trunc('12.a'); // Cannot be correctly converted to numeric type, return NaN console.log(sample, sample1,sample2); // 4, 4 ,NaN
Math.sign()
Math.sign() determines whether a number is positive, negative, or zero. For non numeric values, they are converted to numeric values first.
Five return values are 1, - 1, 0, - 0 and NaN. They represent positive numbers, negative numbers, positive zero, negative zero and NaN.
- If the parameter is a positive number, return + 1;
- If the parameter is negative, return - 1;
- If the parameter is 0, return 0;
- If the parameter is - 0, return - 0;
- Other values, return NaN.
const sample = Math.sign(-4); // -1 negative const sample1 = Math.sign(4); // 1 positive number const sample2 = Math.sign(0); // 0 0 const sample3 = Math.sign(-0); // -0 -0 const sample4 = Math.sign('a'); // NaN non numeric console.log(sample, sample1, sample2, sample3, sample4); // -1, 1, 0, -0, NaN
Math.cbrt()
Mathematically: if x ³= a. Then x is called the cube root of A.
Math.cbrt() calculates the cube root of a number
const sample = Math.cbrt(-1); const sample1 = Math.cbrt(8); const sample2 = Math.cbrt(0); // The cube root of 0 is 0 const sample3 = Math.cbrt(-0); const sample4 = Math.cbrt('a'); // For non numeric types, first call Number to convert to numeric type console.log(sample, sample1, sample2, sample3, sample4); // -1, 2, 0, -0, NaN
Math.clz32()
The Math.clz32() function returns the number of zeros at the beginning of a 32-bit unsigned integer number,
For null values or other types of values, the Math.clz32 method converts them to numeric values before calculating them.
be careful
- Math.clz32() for decimals, only the integer part is considered
- < < operator shifts all bits of [number to be displaced] to the left by the number of bits specified by [number of displacement bits].
- result = [number to be displaced] < < number of displacement digits]
const sample = Math.clz32(); // Convert null to value 0 const sample1 = Math.clz32(1 << 29); // Left shift operator change const sample2 = Math.clz32(44.7); // Only integer parts are considered const sample3 = Math.clz32(true); // Convert to value 1 const sample4 = Math.clz32('a'); // For non numeric types, first call Number to convert to numeric type console.log(sample, sample1, sample2, sample3, sample4); // 32, 2, 26, 31, 32
Math.imul()
The Math.imul() method converts the two parameters into 32-bit integers respectively, and multiplies them to return a 32-bit signed integer.
JavaScript has a precision limit, so that values exceeding the 53rd power of 2 cannot be accurately represented. The Math.imul() method can return the correct low-order value.
const sample = Math.imul(-1, 8.9); // If the parameter has a decimal, it will be converted to an integer first const sample1 = Math.imul(0xffffffff, 5); // The following parameters can also be displayed correctly if their product exceeds the 53rd power of 2 const sample2 = Math.imul(0x7fffffff, 0x7fffffff); console.log(sample, sample1, sample2); // -8, -5, 1
Math.fround()
Math.fround() can convert any number to a 32-bit single precision floating-point number.
JavaScript internally uses 64 bit double floating-point numbers and supports high precision. For the 32-bit single precision format, the numerical precision is 24 binary bits (1-bit hidden bit and 23 bit significant bit)
be careful
- If the absolute value of the parameter is greater than 224, the returned result begins to lose precision.
- For NaN and Infinity, this method returns the original value
- For other non numeric values, the Math.fround method first converts them to numeric values, and then returns single precision floating-point numbers.
const sample = Math.fround(99); const sample1 = Math.fround(0.7); // Lost accuracy const sample2 = Math.fround('5'); const sample3 = Math.fround(Infinity); console.log(sample, sample1, sample2, sample3); // Output 99, 0.69999988079071, 5, infinity
Math.hypot()
The Math.hypot() function returns the square root of the sum of squares of all parameters.
const sample = Math.hypot(3, 4); // Square root of 2 * 2 + 2 * 2 const sample1 = Math.hypot(); // 0 null converted to value 0 const sample2 = Math.hypot('-9'); const sample3 = Math.hypot(Infinity); // Non numeric types are converted to numeric types first const sample4 = Math.hypot(1, 2, 'a'); // NaN is returned whenever a parameter cannot be converted to a value. console.log(sample, sample1, sample2, sample3, sample4); // 5, 0, 9, Infinity, NaN
Logarithmic method
Math.expm1()
Math.expm1() returns ex - 1, that is, Math.exp(x) - 1, where x is the parameter of the function and e is the base of the natural logarithm
const sample = Math.expm1(-38); const sample1 = Math.expm1(0); const sample2 = Math.expm1(1); const sample3 = Math.expm1('a'); console.log(sample, sample1, sample2, sample3); // -1, 0, 1.718281828459045, NaN
Math.log1p()
The Math.log1p() method returns the natural logarithm after the parameter + 1, (the bottom is e), that is, Math.log(1 + x).
const sample = Math.log1p(-2); // If the parameter is less than - 1, NaN is returned const sample1 = Math.log1p(-1); // -1 + 1 = 0 returns - Infinity 0 has no logarithm const sample2 = Math.log1p(0); // 0 + 1 = 1 the logarithm of 1 is 0 const sample3 = Math.log1p('a'); console.log(sample, sample1, sample2, sample3); // NaN, -Infinity, 0, NaN
Math.log10()
Math.log10() returns the base 10 logarithm of the parameter
const sample = Math.log10(-2); // If the parameter is less than 0, NaN is returned const sample1 = Math.log10(1); // The logarithm of 1 is 0 const sample2 = Math.log10('10'); // Convert to numeric type const sample3 = Math.log10('a'); console.log(sample, sample1, sample2, sample3); // NaN, 0, 1, NaN
Math.log2()
Math.log10() is similar to Math.log2(). One is based on 10 and the other is based on 2
Math.log2() returns the base 2 logarithm of the parameter
const sample = Math.log2(-2); // If the parameter is less than 0, NaN is returned const sample1 = Math.log2(1); // The logarithm of 1 is 0 const sample2 = Math.log2('1024'); // Convert to numeric type const sample3 = Math.log2('a'); console.log(sample, sample1, sample2, sample3); // NaN, 0, 10, NaN
Hyperbolic function method
ES6 adds 6 hyperbolic function methods.
- The Math.sinh() function returns the hyperbolic sine of a number in angle.
- The Math.cosh() function returns the hyperbolic cosine function of a numeric value, which can be represented by constant e.
- The Math.tanh() function returns the hyperbolic tangent function value of a number.
- The Math.asinh() function returns the inverse hyperbolic sine of a given number.
- Math.acosh() returns the inverse hyperbolic cosine of a number.
- The Math.atanh() function returns a numeric inverse hyperbolic tangent.
BigInt data type
describe
ES2020 introduces a new data type BigInt, which is the eighth data type of ECMAScript.
BigInt is only used to represent integers. There is no limit on the number of bits. Integers with any number of bits can be accurately represented.
The purpose of the BigInt data type is a wider range of integer values than the Number data type supports.
be careful
- BigInt can also be expressed in various hexadecimals, with the suffix n.
- BigInt and Number values are of different types.
- BigInt can use all operators except the unary plus sign (+) operator.
- BigInt can also be converted to other data types.
- BigInt cannot be mixed with ordinary values.
const sample = 99999999999999999999n; // Can represent an integer of any length const sample1 = 999n + 999n * 99n / 99n - 99n; // You can use all operators except the unary plus sign const sample2 = 0o777n + 0b1101n; // It can be represented by various hexadecimals const sample3 = String(1n); // Conversion to other types of data n will disappear console.log(sample); // 99999999999999999999n console.log(sample1); // 1899n console.log(sample2); // 524n console.log(sample3); // 1 const sample4 = 10n + 10; // Direct error reporting cannot be mixed with ordinary values.
BigInt function
JavaScript native provides BigInt function to convert other types of values to BigInt type. Consistent with Number()
be careful
- Parameter cannot be empty.
- Parameter cannot be decimal.
- Parameters must be able to be converted to values normally.
const sample = BigInt(44); const sample1 = BigInt('490'); // It can be converted correctly console.log(sample); // 44n console.log(sample1); // 490n // All errors are reported below const sample2 = BigInt(undefined); const sample3 = BigInt('44a'); // Convert value to NaN const sample4 = BigInt(1.1); // An error is reported when the parameter is decimal const sample5 = BigInt(); // Empty