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);
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
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);
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
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
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
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); }
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
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
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
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; }
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!

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)
