Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of JavaScript data structure Number

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article editor for you to introduce in detail "JavaScript data structure Number case analysis", the content is detailed, the steps are clear, the details are handled properly, I hope this "JavaScript data structure Number case analysis" article can help you solve your doubts, following the editor's ideas slowly in depth, together to learn new knowledge.

Foreword:

Number is the basic data structure of JavaScript and the application type of corresponding values. To create a Number object, use the Number constructor and pass in a numeric value. There are not as many numeric types in other languages in JavaScript. According to the ECMAScript standard, there is only one type of number, which is a "double precision 64-bit binary format IEEE 754 value". This type is used to store integers and fractions and is 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 introduces common problems with JavaScript using Number.

Let's take a look at the following code:

Console.log (0.1 + 0.2); / / 0.300000000000004

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

1. NaN and Infinity

NaN stands for Not a Number and is different from Infinity, although both are usually treated as special cases in floating-point representations of real numbers and floating-point operations. NaN is a special value, which is the only value that is not equal to itself. take a look at the following code to understand one of this value:

Const num = 9 + NaN;console.log (num); / / NaNconsole.log (NaN = = NaN); / / falseconsole.log (NaN = NaN); / / falseconsole.log (Object.is (NaN, NaN)); / / trueconsole.log (isNaN (NaN)); / / trueconsole.log (isNaN ("devpoint")); / / trueconsole.log (Number.isNaN (NaN)); / / trueconsole.log (Number.isNaN ("devpoint")) / / falseconsole.log (Number.isNaN (+ "devpoint")); / / true

Infinity is a special value in JavaScript that represents mathematical infinity and overflow values, and the number is so large that it "overflows" the buffer and causes Infinity. It is the result of a calculation that creates a number that exceeds the special maximum value in JavaScript, which is approximately 1.79e+308 or 2} ², that is, the maximum value that can be stored in JavaScript as the original type of the number.

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

2. Common methods

It is a common requirement to process numbers in a program, such as serial number, cost, temperature, and so on. The following shows some common Number-related methods through code.

1. Safe number

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

What is the range of safe numbers in JavaScript? How to verify it?

Number.MIN_SAFE_INTEGER:-9007199254740991

Number.MAX_SAFE_INTEGER:9007199254740991

Number.MAX_VALUE:1.7976931348623157e+308

Number.MIN_VALUE: `5e-324

Const test = 900719925474099194 console.log (Number.isSafeInteger (test)); / / falseconsole.log (Number.isSafeInteger (9007199254740991)); / / true2. Integer judgment

In JavaScript, numbers do not distinguish between integers, decimals and other types, collectively referred to as the Number type. You can think of a way to judge integers from the following code results:

Console.log (Number.isInteger (9)); / / trueconsole.log (Number.isInteger (9 / 2)); / / falseconsole.log (Number.isInteger (9.6)); / / falseconsole.log (9% 1 = = 0); / / trueconsole.log (9.1% 1 = 0); / / falseconst checkInteger = (num) = > (num | 0) = num;console.log (checkInteger (9)); / / trueconsole.log (checkInteger (9.1)) / / falseconsole.log (checkInteger ("9.0")); / / falseconsole.log (checkInteger (")); / / false3. Digital format judgment

The following code snippet shows how to check whether a value or variable contains a number (integer, floating point, and so on).

Function isNumber (n) {return! isNaN (parseFloat (n)) & & isFinite (n);} console.log (isNumber); / / trueconsole.log (isNumber (3.14)); / / trueconsole.log (isNumber ("3.14")); / / trueconsole.log (isNumber ("a3.14")); / / falseconsole.log (isNumber ("JavaScript")); / / false4. Round off

In JavaScript, there are many ways to round numbers, so let's summarize them one by one.

Round up:

Rounding up uses Math.ceil () to return the integer that is greater than or equal to x and is closest to it.

Console.log (Math.ceil (9.005)) / / 10console.log (Math.ceil (9.999)); / / 10

Round off:

Math.round () rounds a floating-point number and retains integer bits. The syntax is as follows:

Math.round (x)

X: values to be processed

Returns the rounded value of a given number.

Console.log (Math.round (9.005)); / / 9console.log (Math.round (9.51); / 10console.log (Math.round (9.49)); / / 9console.log (Math.round (9.999)); / / 10

Fixed precision:

.tofixed () is a method implemented on the Number prototype that rounds a floating point number and retains a fixed decimal place. The syntax is as follows:

NumObj.toFixed (digits)

Digits: the number of digits after the decimal point; between 0 and 20 (inclusive), the implementation environment may support a wider range. If you omit this parameter, the default is 0.

Returns a value that returns a string that represents a given number in fixed-point notation.

Const pi = 3.14159265359 console.log (pi.toFixed (2)); / / 3.14console.log (pi.toFixed (3)); / / 3.142

Fixed length:

ToPrecison () is also a method of dealing with floating-point numbers implemented on the Number prototype. Unlike toFixed, it is a valid number that rounds a floating-point number and retains a fixed length, including integer parts. The syntax is as follows:

NumObj.toPrecision (precision)

Precision: optional, an integer used to specify a valid number.

Returns a value, expressed as a string of numeric objects in fixed-point or exponential representation, rounded to the number of display digits specified by the precision parameter.

Const pi = 3.14159265359 console.log (pi.toPrecision (3)); / / 3.14console.log (pi.toPrecision (4)); / / 3.142

Round down:

Math.floor () returns the largest integer less than or equal to a given number.

Math.floor (x)

X: a number.

Returns a number that represents the largest integer less than or equal to the specified number.

Console.log (Math.floor (9.005)); / 9console.log (Math.floor (9.51)); / 9console.log (Math.floor (9.49)); / / 9console.log (Math.floor (9.999)); / / 95. Generate random number

Through the principle that Math.random () returns a random number between 0 and 1, the result is multiplied by the maximum number and rounded to get a number between 0 and max.

Const randomNumber = (max) = > Math.round (Math.random () * max); console.log (randomNumber

Further refine the above method to obtain the specified minimum and maximum range of random numbers.

Const randomNumber = (min, max) = > Math.round (Math.random () * (max-min) + min); console.log (randomNumber (51,100))

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

After reading this, the article "Number instance Analysis of JavaScript data structure" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report