Home > Web Front-end > JS Tutorial > Fun with JavaScript Numbers

Fun with JavaScript Numbers

Lisa Kudrow
Release: 2025-02-24 10:17:10
Original
443 people have browsed it

Fun with JavaScript Numbers

Key Points

  • All numbers in JavaScript are represented using the Number data type, including integers, real numbers, hexadecimal numbers, and scientific notation numbers. However, JavaScript internally represents all numbers as IEEE 754 floating point numbers, which means that JavaScript math is not 100% accurate.
  • JavaScript defines a number called Not-a-Number (NaN) to represent non-digits as numbers. NaN is the only numeric value in JavaScript that is not equal to itself, and can be tested using the isNaN() function.
  • JavaScript has some features, such as signed zeros, resulting in positive zeros (0) and negative zeros (-0), which are considered different values, but JavaScript's comparison operators cannot distinguish them. In JavaScript, dividing by zero produces Infinity, and dividing by negative zero produces -Infinity.

Data types are an important part of every programming language, and numbers are perhaps the most important data types. After all, computers are really just expensive calculators. Like any valuable programming language, JavaScript supports numerical data. But, like many other aspects of JavaScript, there are some nuances in numbers that can cause you trouble if you are not careful. This article discusses numerical data and some of its characteristics. Note: Before reading this article, you should have a basic understanding of JavaScript data types .

Number Type

In JavaScript, all numbers are represented by the Number data type. This includes integers, real numbers, hexadecimal numbers and numbers represented by scientific notation. The following example verifies this by applying the typeof operator to various numbers. In this example, each application of typeof returns a number.

typeof(100);
typeof(3.14);
typeof(0xDEADBEEF);
typeof(7.89e2);
Copy after login
Copy after login

In the previous example, the numbers are in various formats. However, internally, all JavaScript numbers are actually represented as IEEE 754 floating point numbers. This is important because it means that JavaScript does not have the concept of integers, although the language has the parseInt() function. This also means that JavaScript math operations are not 100% accurate. For example, consider the following expression.

(0.1 + 0.2) === 0.3
Copy after login
Copy after login

If you are not familiar with floating point numbers, you will definitely expect this expression to evaluate to true. After all, 0.1 0.2 equals 0.3. However, due to how floating point numbers work, their sum is actually 0.30000000000000000000004. The difference is small, but this is enough to cause the entire expression to evaluate to false.

Positive zero and negative zero

Another feature of the IEEE 754 standard is the signed zero. This results in two zeros - positive zero, 0, and negative zero, -0. This may seem strange, but the fun has just begun. Obviously, these two are different values, otherwise there will be only one zero. However, if you show either of these two zeros, the symbol will be deleted. For example, the following code tries to display these two zero values ​​side by side.

typeof(100);
typeof(3.14);
typeof(0xDEADBEEF);
typeof(7.89e2);
Copy after login
Copy after login

Worse, JavaScript's comparison operators also seem to be unable to distinguish between the two values, as shown in the following example.

(0.1 + 0.2) === 0.3
Copy after login
Copy after login

There is a fairly simple solution to this problem. In JavaScript, dividing by zero produces an Infinity. Likewise, dividing by negative zero will produce -Infinity. So to determine if a number is equal to -0, we have to check if it is zero, then use it as the denominator for division and check -Infinity as shown below.

alert((+0) + " " + (-0));
// 显示 0 0
Copy after login

Not-a-Number (NaN)

JavaScript actually defines a number called Not-a-Number (NaN). NaN is a false value used to represent non-digits as numbers. This value is interesting because its name itself rules out the possibility that it is a number, but typeof(NaN) is number. NaN is also interesting because it is the only value in JavaScript that does not equal itself. For example, the following code will return false.

alert((+0 === -0));
// 显示 true
alert((-0 === +0)); // 显示 true
Copy after login

You can test NaN using the isNaN() function instead of using the comparison operator as shown below.

function isNegativeZero(x) {
  return (x === 0 && (1/x) === -Infinity);
}
Copy after login

However, isNaN() is also interesting because it can be misleading. If you pass in a value that can be cast to a number, isNaN() will return false. In the following example, isNaN() is called with several values ​​that are obviously not numeric. However, every call returns false.

alert((NaN === NaN));
// 显示 false
Copy after login

A better way to check NaN is to take advantage of the fact that it does not equal itself. The following function tests NaN using strict inequality. This function returns true only for the value NaN.

isNaN(1);
// 返回 false
isNaN(NaN);
// 返回 true
Copy after login

Other fun moments

There are some other situations that may cause problems with the numbers. First, you should be aware of old browsers, which allow global properties such as Infinity, NaN, and undefined to be redefined as new values. For example, if you use NaN frequently, the following code can cause many problems. Fortunately, modern browsers ignore assignments to the aforementioned properties. Strict mode goes a step further, converting these silent failures into errors.

isNaN(true);
isNaN(false);
isNaN("");
isNaN(null);
// 全部返回 false
Copy after login

Another interesting diagnostic error comes from adding numbers and strings. An example is shown below. In this case, string concatenation overrides the addition. This causes foo to be converted to the string "100". The end result is the string "1001", which is very different from the expected value of 101. This type of error is more common than you think and often occurs when reading user input.

function isNotANumber(x) {
  return x !== x;
}
Copy after login

Conclusion

This article discusses some of the characteristics of numbers in JavaScript. Hopefully you now understand how these problems arise and how to avoid them. And, while you may not often encounter situations like negative zeros, at least now you are ready.

Frequently Asked Questions about JavaScript Numbers (FAQ)

What happens when dividing a number by zero in JavaScript?

In JavaScript, when you divide the number by zero, the result is Infinity. This is because any number divided by zero is mathematically undefined, but JavaScript represents it as Infinity for practical purposes. However, if you divide zero by zero, the result is NaN (Not a Number), because this operation is uncertain in mathematics.

How to deal with BigInt divided by zero?

BigInt is a built-in object in JavaScript that provides a way to represent integers larger than 2^53-1, the largest number that JavaScript can reliably represent using the Number primitive. If you try to divide BigInt by zero, JavaScript will throw a RangeError indicating that the operation is invalid.

How to prevent or handle division by zero error in JavaScript?

You can use conditional statements in JavaScript to prevent or process division by zero errors by checking whether the denominator is zero before performing the division operation. If the denominator is zero, you can decide how to handle it, for example, return a specific value or display an error message.

Why is 0 divided by 0 in JavaScript NaN?

In mathematics, the expression 0/0 is undefined because it does not have an explicit, definite value. In JavaScript, undefined mathematical operations result in NaN (Not a Number). So when you divide zero by zero in JavaScript, the result is NaN.

What is the difference between NaN and Infinity in JavaScript?

In JavaScript, NaN (Not a Number) and Infinity are special values. NaN represents a value that is not a legal number, usually due to undefined or uncertain mathematical operations. Infinity, on the other hand, represents a number larger than any possible number, usually due to dividing the number by zero.

How to check if the result in JavaScript is NaN?

You can use the isNaN() function in JavaScript to check whether the result is NaN. If the parameter is NaN, this function returns true, otherwise false.

How to check if the result in JavaScript is Infinity?

You can use the isFinite() function in JavaScript to check if the result is a finite number. If the parameter is positive or negative infinity, this function returns false, otherwise true.

What is the meaning of the Number primitive in JavaScript?

The Number primitive in JavaScript is used to represent numeric values. It can represent integer values ​​and floating point numbers. However, it can only reliably represent numbers up to 2^53-1.

How to deal with large numbers in JavaScript?

To handle large numbers that exceed the JavaScript secure integer limit, you can use BigInt objects. BigInt allows you to represent integers greater than 2^53-1.

What is RangeError in JavaScript?

JavaScript throws a RangeError when the value is not within the expected range. For example, trying to divide BigInt by zero results in a RangeError.

The above is the detailed content of Fun with JavaScript Numbers. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template