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

Two uses of the Number() method in JavaScript

hzc
hzcforward
2020-06-22 10:43:027322browse

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)

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)

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.

Properties

  • Number.MAX_VALUE represents the maximum positive value
  > Number.MAX_VALUE
  1.7976931348623157e+308
  • Number.MIN_VALUE represents the smallest positive value
> Number.MIN_VALUE
5e-324
  • 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'
  • Number.prototype.toPrecision(precision?)
> 1234..toPrecision(3)
'1.23e+3'
  • Number.prototype.toString(radix?)
> 15..toString(2)
'1111'
> 65535..toString(16)
'ffff'
  • 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!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete