In JS, there are two main ways to call Number(). One is as a function to convert any type of data into a numerical value. The second is as a class to generate a numerical object through new.
The first method is more commonly used.
Number(value)
Convert any type of data into a numerical value. If it cannot be converted, NaN is returned. The conversion rules are similar to type implicit Conversion, slightly different from parseFloat
.
The conversion rules are as follows:
ValueValue | Result |
---|---|
undefined | NaN |
null | 0 |
false | 0 |
true | 1 |
number | Output as is |
string | Ignore leading and trailing spaces until the first non-numeric character is encountered. The empty string returns 0 |
object | Call Internal ToPrimitive(value, Number), if it is a Date object, returns the number of milliseconds from January 1, 1970 to Date |
new Number(num)
As a constructor, generates a Number instance, wraps num (after converting it to a number).
For example:
> typeof new Number(3) 'object'
Since it is an object , there must be related properties and methods, and Number is no exception.
> Number.MAX_VALUE 1.7976931348623157e+308
> Number.MIN_VALUE 5e-324
All native numerical related functions are saved in the object prototype (Number.prototype) and can be called directly.
> 0.0000003.toFixed(10) '0.0000003000'
> 1234..toPrecision(3) '1.23e+3'
> 15..toString(2) '1111' > 65535..toString(16) 'ffff'
Recommended tutorial: "JS Tutorial"
The above is the detailed content of Two uses of the Number() method in JavaScript. For more information, please follow other related articles on the PHP Chinese website!