SoFunction
Updated on 2025-03-10

JavaScript data structure Number

Preface:

NumberyesJavaScriptThe basic data structure is the application type of corresponding numerical values. To create a Number object, use the Number constructor and pass in a numeric value. There is no other language in JavaScript that has so many numeric types. According to the ECMAScript standard, there is only one type of a number, which is a "double-precision 64-bit binary format IEEE 754 value". This type is used to store integers and fractions, equivalent to the double data type in Java and C. This uniqueness also leads to why 0.1+0.2 is not equal to 0.3. This article describes the common problems of using Number in JavaScript.

Let’s take a look at the following code:

(0.1 + 0.2); // 0.30000000000000004

From the above running results, we can see that 0.1+0.2 does not equal 0.3. Only fractions with powers with denominators 2 can be expressed finitely as binary. Since the denominators 0.1 (1 / 10) and 0.2 (1 / 5) are not powers of 2, these numbers cannot be expressed finitely in binary format. In order to store them as IEEE-754 floating point numbers, they must round to the available digits of the mantissa—half precision is 10 bits, single precision is 23 bits and double precision is 52 bits. Depending on the number of precision bits available, floating point approximations of 0.1 and 0.2 may be slightly smaller or slightly larger than the corresponding decimal representation, but will never be equal. Because of this fact, there will never be 0.1+0.2 == 0.3.

1. NaN and Infinity

NaN stands forNot a Number And it's different fromInfinity, although both are usually handled as special cases in floating point representations of real numbers and floating point operations. NaN is a special value, it is the only value that is not equal to itself.Let's take a look at the following code to understand a value:

const num = 9 + NaN;
(num); // NaN
(NaN == NaN); // false
(NaN === NaN); // false
((NaN, NaN)); // true
(isNaN(NaN)); // true
(isNaN("devpoint")); // true
((NaN)); // true
(("devpoint")); // false
((+"devpoint")); // true

Infinity is a special value in JavaScript that represents mathematical infinity and overflow values, the number is too large to "overflow" the buffer and lead to Infinity. It is the result of calculating the creation of a number that exceeds the special maximum in JavaScript, which is about 1.79e+308 or 2¹⁰²⁴, which is the maximum value in JavaScript that can be stored as a numeric primitive type.

Notice :Infinity, -Infinity and NaN are the only "infinite" (non-finite) numbers in JavaScript.

2. Common methods

Handling numbers in programs is a common requirement, such as serial numbers, fees, temperatures, etc. The following is a code to show some commonly used methods related to Number.

1. Safe Numbers

A safe number is a number whose value is guaranteed to be displayed normally. For example, if there is a variable value of 900719925474099194 , is it safe?

Let’s take a look at the following: What is the range of safe numbers in JavaScript? How to verify?

  • Number.MIN_SAFE_INTEGER:-9007199254740991
  • Number.MAX_SAFE_INTEGER:9007199254740991
  • Number.MAX_VALUE:1.7976931348623157e+308
  • Number.MIN_VALUE:`5e-324
const test = 900719925474099194;
((test)); // false
((9007199254740991)); // true

2. Integer judgment

existJavaScriptThe numbers do not distinguish between integers, decimals and other types, and are collectively called the Number type. From the following code results, you can think of a way to judge integers:

((9)); // true
((9 / 2)); // false
((9.6)); // false
(9 % 1 === 0); // true
(9.1 % 1 === 0); // false
const checkInteger = (num) => (num | 0) === num;
(checkInteger(9)); // true
(checkInteger(9.1)); // false
(checkInteger("9.0")); // false
(checkInteger("")); // false

3. Number format judgment

The following code snippet will show how to check if a value or variable contains a number (integral, floating point number, etc.).

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
(isNumber(100)); // true
(isNumber(3.14)); // true
(isNumber("3.14")); // true
(isNumber("a3.14")); // false
(isNumber("JavaScript")); // false

4. Rounding

existJavaScript There are many ways to round the numerical values, so let’s summarize them one by one.

Round upward:

Round up(), returns the integer greater than or equal to x and closest to it.

((9.005)); // 10
((9.999)); // 10

rounding:

() It is to round a floating point number and preserve integer bits.The syntax is as follows:

(x)

x: The value to be processed

Returns the value, which returns the rounded value of the given number.

((9.005)); // 9
((9.51)); // 10
((9.49)); // 9
((9.999)); // 10

Fixed accuracy:

.toFixed()yesNumberA method implemented on the prototype is to round a floating point number and retain a fixed decimal place. The syntax is as follows:

(digits)

digits:The number of numbers after the decimal point; between 0 and 20 (inclusive), the implementation environment may support a larger range. If this parameter is ignored, the default is 0.
Returns the value, returning a string that uses fixed-point notation to represent the given number.

const pi = 3.14159265359;
((2)); // 3.14
((3)); // 3.142

Fixed length:

.toPrecison() It is also a method of processing floating-point numbers implemented on the Number prototype. Unlike toFixed, it rounds a floating-point number and retains a fixed-length significant number, including the integer part.The syntax is as follows:

(precision)

precision: Optional, an integer that specifies a significant number.
Returns the value, represented as a string of a numeric object represented by fixed-point representation or exponential representation, rounded to the number of displayed digits specified by the precision parameter.

const pi = 3.14159265359;
((3)); // 3.14
((4)); // 3.142

Round downward:

() Returns the maximum integer less than or equal to a given number.

(x)

x: a number.

Returns a value, a number representing the largest integer less than or equal to the specified number.

((9.005)); // 9
((9.51)); // 9
((9.49)); // 9
((9.999)); // 9

5. Generate random numbers

pass() Return the principle of random numbers between 0-1, multiply the result by the maximum number and round it to get a number between 0 and max.

const randomNumber = (max) => (() * max);
(randomNumber(100));

Further improve the above method so that you can get random numbers with the specified minimum and maximum range.

const randomNumber = (min, max) =>
    (() * (max - min) + min);
    (randomNumber(51, 100));

Mathematical functionsMathis a built-in object that has some mathematical constant properties and mathematical function methods. Math is not a function object. Math is used for the Number type, but it does not support BigInt.

3. Summary

JavaScriptofNumber Objects are encapsulated objects that allow you to process numeric values. It introduces the only "infinite" (non-finite) numbers in JavaScript: Infinity, -Infinity and NaN, and provides some commonly used digital processing methods.

This is all about this article about JavaScript data structure Number. For more related JavaScript-Number content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!