Number

Overview

The Number object is a packaging object corresponding to the value, which can be used as a constructor function or as a tool function.

As a constructor, it is used to generate objects whose values ​​are numeric values.

var n = new Number(1);
typeof n; // "object"

In the above code, the Number object is used as a constructor and returns an object with a value of 1.

As a tool function, it can convert any type of value into a numeric value.

Number(true); // 1

The above code converts the boolean value true to the value 1. For the usage of Number as a utility function, see the chapter "Data Type Conversion" for details.

Static properties

The Number object has the following static properties (that is, the properties directly defined on the Number object, not the properties defined on the instance).

-Number.POSITIVE_INFINITY: Positive infinity, pointing to Infinity. -Number.NEGATIVE_INFINITY: negative infinity, pointing to -Infinity. -Number.NaN: Represents not a number, pointing to NaN. -Number.MIN_VALUE: Represents the smallest positive number (that is, the positive number closest to 0, which is 5e-324 in the 64-bit floating point number system), and the corresponding negative number closest to 0 is -Number.MIN_VALUE . -Number.MAX_SAFE_INTEGER: Represents the largest integer that can be accurately represented, that is, 9007199254740991. -Number.MIN_SAFE_INTEGER: Represents the smallest integer that can be accurately represented, namely -9007199254740991.

Number.POSITIVE_INFINITY; // Infinity
Number.NEGATIVE_INFINITY; // -Infinity
Number.NaN; // NaN

Number.MAX_VALUE;
// 1.7976931348623157e+308
Number.MAX_VALUE < Infinity;
// true

Number.MIN_VALUE;
// 5e-324
Number.MIN_VALUE > 0;
// true

Number.MAX_SAFE_INTEGER; // 9007199254740991
Number.MIN_SAFE_INTEGER; // -9007199254740991

Example method

The Number object has 4 instance methods, all of which are related to converting a value into a specified format.

Number.prototype.toString()

The Number object deploys its own toString method to convert a number into a string form.

(10).toString(); // "10"

The toString method can accept one parameter, which represents the base of the output. If this parameter is omitted, the value will be converted to decimal by default, and then the string will be output; otherwise, a number will be converted into a string of a certain hexadecimal according to the hexadecimal specified by the parameter.

(10)
  .toString(2)(
    // "1010"
    10
  )
  .toString(8)(
    // "12"
    10
  )
  .toString(16); // "a"

In the above code, 10 must be placed in parentheses, which indicates that the following dots indicate the properties of the calling object. If the parentheses are not added, this point will be interpreted as a decimal point by the JavaScript engine and an error will be reported.

10.toString(2)
// SyntaxError: Unexpected token ILLEGAL

As long as the JavaScript engine can not confuse the decimal point and the point operator of the object, various writing methods can be used. In addition to adding parentheses to 10, you can also add two dots after 10. JavaScript will interpret the first point as a decimal point (that is, 10.0), and the second point as calling object properties, thus Get the correct result.

(10).toString(2);
// "1010"

// other methods include
(10).toString(2); // "1010"
(10.0).toString(2); // "1010"

This actually means that you can use the toString method directly on a decimal.

(10.5).toString(); // "10.5"
(10.5).toString(2); // "1010.1"
(10.5).toString(8); // "12.4"
(10.5).toString(16); // "a.8"

The toString method can also be called by the square bracket operator.

(10)["toString"](2); // "1010"

The toString method can only convert decimal numbers into strings in other bases. If you want to convert numbers in other bases back to decimal, you need to use the parseInt method.

Number.prototype.toFixed()

The toFixed() method first converts a number to a specified number of decimals, and then returns the string corresponding to this decimal.

(10).toFixed(2); // "10.00"
(10.005).toFixed(2); // "10.01"

In the above code, 10 and 10.005 are first converted to 2 decimal places, and then converted to a string. Among them, 10 must be placed in parentheses, otherwise the following points will be treated as decimal points.

The parameter of the toFixed() method is the number of decimal places, and the valid range is from 0 to 100. If it exceeds this range, a RangeError will be thrown.

Due to the floating point number, the rounding of the decimal number 5 is uncertain, so you must be careful when using it.

(10.055)
  .toFixed(2)(
    // 10.05
    10.005
  )
  .toFixed(2); // 10.01

Number.prototype.toExponential()

The toExponential method is used to convert a number into scientific notation form.

(10)
  .toExponential()(
    // "1e+1"
    10
  )
  .toExponential(1)(
    // "1.0e+1"
    10
  )
  .toExponential(2)(
    // "1.00e+1"

    1234
  )
  .toExponential()(
    // "1.234e+3"
    1234
  )
  .toExponential(1)(
    // "1.2e+3"
    1234
  )
  .toExponential(2); // "1.23e+3"

The parameter of the toExponential method is the number of significant digits after the decimal point, ranging from 0 to 100. If it exceeds this range, a RangeError will be thrown.

Number.prototype.toPrecision()

The Number.prototype.toPrecision() method is used to convert a number to a specified number of significant numbers.

(12.34)
  .toPrecision(1)(
    // "1e+1"
    12.34
  )
  .toPrecision(2)(
    // "12"
    12.34
  )
  .toPrecision(3)(
    // "12.3"
    12.34
  )
  .toPrecision(4)(
    // "12.34"
    12.34
  )
  .toPrecision(5); // "12.340"

The parameter of this method is the number of significant digits, and the range is 1 to 100. If it exceeds this range, a RangeError will be thrown.

This method is not very reliable when used for rounding, and is related to the fact that floating-point numbers are not accurately stored.

(12.35)
  .toPrecision(3)(
    // "12.3"
    12.25
  )
  .toPrecision(3)(
    // "12.3"
    12.15
  )
  .toPrecision(3)(
    // "12.2"
    12.45
  )
  .toPrecision(3); // "12.4"

Number.prototype.toLocaleString()

The Number.prototype.toLocaleString() method accepts a locale code as a parameter and returns a string representing the local writing form of the current number in the locale.

(123).toLocaleString("zh-Hans-CN-u-nu-hanidec");
// "one two Three"

This method can also accept a second parameter configuration object to customize the return string for a specific purpose. The style attribute of this object specifies the output style. The default value is decimal, which means the output is in decimal format. If the value is percent, it means the output percentage.

(123).toLocaleString("zh-Hans-CN", { style: "percent" });
// "12,300%"

If the value of the style attribute is currency, it can be used with the currency attribute to output the currency string in the specified format.

(123)
  .toLocaleString("zh-Hans-CN", { style: "currency", currency: "CNY" })(
    // "¥123.00"

    123
  )
  .toLocaleString("de-DE", { style: "currency", currency: "EUR" })(
    // "123,00 €"

    123
  )
  .toLocaleString("en-US", { style: "currency", currency: "USD" });
// "$123.00"

If the parameter is omitted in Number.prototype.toLocaleString(), the browser decides how to deal with it, and usually uses the locale setting of the operating system. Note that if this method uses an area code that the browser does not recognize, an error will be thrown.

(123).toLocaleString("123"); // error

Custom method

Like other objects, the methods on the Number.prototype object can be customized, which are inherited by instances of Number.

Number.prototype.add = function (x) {
  return this + x;
};

(8)["add"](2); // 10

The above code defines an add method for the Number object instance. If you call a method on a value, the value will be automatically converted to an instance of Number, so you can call the add method. Since the add method returns a value, it can be chained.

Number.prototype.subtract = function (x) {
  return this - x;
};

(8).add(2).subtract(4);
// 6

The above code deploys the subtract method on the instance of the Number object, which can be called in a chain with the add method.

We can also deploy more complex methods.

Number.prototype.iterate = function () {
  var result = [];
  for (var i = 0; i <= this; i++) {
    result.push(i);
  }
  return result;
};

(8).iterate();
// [0, 1, 2, 3, 4, 5, 6, 7, 8]

The above code deploys the iterate method on the prototype of the Number object to automatically traverse a value into an array.

Note that the custom method of the value can only be defined on its prototype object Number.prototype, and the value itself cannot be customized.

var n = 1;
nx = 1;
nx; // undefined

In the above code, n is a primitive type value. Add a property x directly to it, no error will be reported, but it has no effect, and always returns undefined This is because once the attribute is called, n is automatically converted to an instance object of Number, and the object is automatically destroyed after the call is over. Therefore, the next time the property of n is called, another object is actually retrieved, and of course the property x cannot be read.