Home > Web Front-end > JS Tutorial > Two uses of the Number() method in JavaScript

Two uses of the Number() method in JavaScript

hzc
Release: 2020-06-22 10:46:07
forward
7440 people have browsed it

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.


Usage 1: function

Number(value)
Copy after login

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

Usage 2: constructor

new Number(num)
Copy after login

As a constructor, generates a Number instance, wraps num (after converting it to a number).

For example:

> typeof new Number(3)
'object'
Copy after login

Since it is an object , there must be related properties and methods, and Number is no exception.

Properties

  • Number.MAX_VALUE represents the maximum positive value
  > Number.MAX_VALUE
  1.7976931348623157e+308
Copy after login
  • Number.MIN_VALUE represents the smallest positive value
> Number.MIN_VALUE
5e-324
Copy after login
  • Number.NaN is equivalent to global NaN
  • Number .NEGATIVE_INFINITY is the same as -Infinity
  • Number.POSITIVE_INFINITY is the same as Infinity

Methods

All native numerical related functions are saved in the object prototype (Number.prototype) and can be called directly.

  • Number.prototype.toFixed(fractionDigits?)
> 0.0000003.toFixed(10)
'0.0000003000'
Copy after login
  • Number.prototype.toPrecision(precision?)
> 1234..toPrecision(3)
'1.23e+3'
Copy after login
  • Number.prototype.toString(radix?)
> 15..toString(2)
'1111'
> 65535..toString(16)
'ffff'
Copy after login
  • Number.prototype. toExponential(fractionDigits?)

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!

Related labels:
js
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template