search
HomeWeb Front-endJS TutorialNumber type in JS (detailed tutorial)

This article mainly gives you a detailed analysis of the relevant knowledge points of the JavaScript numerical Number type

Number Question

Can you answer the following questions correctly?

  • 0.1 0.2 == 0.3 Is it true?

  • .e-5 means how much? How does

  • represent octal?

  • How to convert base?

  • How to convert a string into a numerical value or integer? What about the other way around? How to deal with hexadecimal?

  • What is the return value of parseInt(0x12, 16)? Is it 0x12?

  • Number.MAX_VALUE is the maximum value. What is (new Number(12)).MAX_VALUE?

  • How to round in JavaScript? How to preserve 3 decimal places of precision?

  • How to get a random number? How to round? How to round up?

Number number representation method

The Number type represents a number, and JavaScript adopts the "double-precision 64-bit format defined by the IEEE 754 standard" IEEE 754 values") represent numbers.

Unlike other programming languages ​​(such as C and Java), JavaScript does not distinguish between integer values ​​and floating point values. All numbers are represented by floating point values ​​in JavaScript, so special attention should be paid when performing numerical operations. Missing progress problem.

0.1 + 0.2 = 0.30000000000000004;
0.1 + 0.2 == 0.3; // false
// 浮点运算判断相等
var ACCURACY = 1e-5; //定义精度精确到0.00001
var a = 0.1;
var b = 0.2;
var sum = 0.3;
// 判断相差小于精度就认为相等
if (a + b - sum < ACCURACY) {
 console.log(&#39;a+b == sum&#39;);
}

In specific implementations, integer values ​​are usually treated as 32-bit integer variables. In individual implementations (such as some browsers), they are also stored in the form of 32-bit integer variables until it is Used to perform certain operations that are not supported by 32-bit integers. This is to facilitate bit operations.

You can omit 0 to represent decimals, or you can use exponential form to represent numbers

.9; // 0.9
1E3 // 1000
2e6 // 2000000
0.1e2 // 10
1e-5 // 0.00001

Number numbers in different bases

Representation methods of different bases

Number can use four numeric bases: decimal, binary, octal and hexadecimal. Only use integers for non-decimal numbers.

  • Binary representation: starting with zero, followed by a lowercase or uppercase Latin letter B (0b or 0B)

  • Octal notation: starting with 0. If the number after 0 is not in the range 0 to 7, the number will be converted to a decimal number.

  • The use of octal syntax is prohibited in ECMAScript 5 strict mode and will be treated as decimal

  • When using octal numbers in ECMAScript 6, you need to give A number is prefixed with "0o"

  • Hexadecimal notation: starting with zero, followed by a lowercase or uppercase Latin letter X (0x or 0X)

// 十进制
12345678
42
0777 // 在非严格格式下会被当做八进制处理 (用十进制表示就是511)
// 二进制
var a = 0b100000; // 32
var b = 0b0111111; // 63
var c = 0B0000111; // 7
// 八进制
var n = 0755; // 493
var m = 0644; // 420
var a = 0o10; // ES6 :八进制
// 十六进制
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF // 81985529216486900
0XA     // 10

Conversion of different bases

Conversion of bases mainly uses the toString() method or parseInt() method of Number:

  • toString() method accepts an integer parameter with a value between 2 and 36 to specify the base. The default is decimal. Convert Number to String

  • parseInt() second The parameter accepts an integer parameter with a value between 2 and 36. The parameter specifies the base system. The default is decimal. Convert the String to Number

// toString转换,输入为Number,返回为String
var n = 120;
n.toString(); // "120"
n.toString(2); // "1111000"
n.toString(8); // "170"
n.toString(16); // "78"
n.toString(20); // "60"
0x11.toString(); // "17"
0b111.toString(); // "7"
0x11.toString(12);// "15"
// parseInt转换,输入为String,返回为Number
parseInt(&#39;110&#39;); // 110
parseInt(&#39;110&#39;, 2); // 6
parseInt(&#39;110&#39;, 8); // 72
parseInt(&#39;110&#39;, 16); // 272
parseInt(&#39;110&#39;, 26); // 702
// toString和parseInt结合使用可以在两两进制之间转换
// 将 a 从36进制转为12进制
var a = &#39;ra&#39;; // 36进制表示的数
parseInt(a, 36).toString(12); // "960"

Number objectNumber

Number object It is a built-in number object that encapsulates a series of Number-related constants and methods.

var na = Number(8); // 8
na = Number(&#39;9.5&#39;); // 9.5
na = new Number(&#39;9.3&#39;); // Number 对象,仅可以使用原型方法

Number object properties:

Properties Description
Number.MAX_VALUE The maximum representable value
Number.MIN_VALUE The minimum representable value
Number.NaN specifically refers to "non-number"
Number.NEGATIVE_INFINITY specifically refers to "negative infinity"; in overflow When it returns
Number.POSITIVE_INFINITY refers specifically to "positive infinity"; when it overflows it returns
Number.EPSILON Represents the difference between 1 and the smallest Number that is closest to 1 and greater than 1
Number.MIN_SAFE_INTEGER JavaScript minimum safe integer
Number.MAX_SAFE_INTEGER JavaScript Maximum Safe Integer

Number对象方法

Number对象方法可以使用 Number. 的形式调用,也可以使用全局调用。

方法 描述
Number.parseFloat() 把字符串参数解析成浮点数,左右等效于一元运算法+
Number.parseInt() 把字符串解析成特定基数对应的整型数字
Number.isFinite() 判断传递的值是否为有限数字
Number.isInteger() 判断传递的值是否为整数
Number.isNaN() 判断传递的值是否为 NaN
Number.isSafeInteger() 判断传递的值是否为安全整数

parseInt() 方法需要注意:

  • parseInt() 参数可以有两个参数:数字字符串和进制

  • 如果第一个参数为非指定进制的数字字符串,则结果为0

  • 如果第一个参数为非字符串,会首先调用该参数的toString()方法转换为字符串

  • 第一个参数中非指定进制可识别的字符会被忽略

  • 如果给定的字符串不存在数值形式,函数会返回一个特殊的值 NaN

  • 如果调用时没有提供第二个参数,则使用字符串表示的数字的进制

parseInt(&#39;123&#39;); // 123
parseInt(&#39;123&#39;, 10); // 123
parseInt(&#39;123&#39;, 8); // 83
parseInt(&#39;123&#39;, 16); // 291
parseInt("11", 2); // 3
parseInt(&#39;0x123&#39;, 10); // 0
parseInt(&#39;0x123&#39;, 16); // 291
parseInt(&#39;0x123&#39;); // 291
// 如果第一个参数不是字符串,会先把第一个参数转成字符串
parseInt(&#39;12&#39;, 16); // 18
parseInt(12, 16); // 18
// toString方法会将数字转换为10进制的字符串
parseInt(0xf, 16); // 21
0xf.toString(); // &#39;15&#39;
parseInt(&#39;15&#39;, 16); // 21
parseInt(&#39;23.56&#39;); // 23
parseInt("hello", 16); // NaN
parseInt("aello", 16); // 174

Number类型原型方法

Number类型原型上还有一些方法来对数字进度进行取舍,这些方法可以被 Number 实例对象调用:

方法 描述
toExponential() 返回一个数字的指数形式的字符串
toFixed() 返回指定小数位数的表示形式
toPrecision() 返回一个指定精度的数字

这些原型方法可以被Number实例对象调用:

var numObj = 12345.6789;
numObj.toExponential(); // "1.23456789e+4"
numObj.toExponential(2); // "1.23e+4"
numObj.toExponential(4); // "1.2346e+4"
numObj.toPrecision();  // "12345.6789"
numObj.toPrecision(2); // "1.2e+4"
numObj.toPrecision(4); // "1.235e+4"
numObj.toFixed();   // 返回 "12346":进行四舍五入,不包括小数部分
numObj.toFixed(1);  // 返回 "12345.7":进行四舍五入
numObj.toFixed(6);  // 返回 "12345.678900":用0填充
(1.23e+20).toFixed(2); // 返回 "123000000000000000000.00"
(1.23e-10).toFixed(2); // 返回 "0.00"
2.34.toFixed(1);   // 返回 "2.3"
-2.34.toFixed(1);   // 返回 -2.3 (由于操作符优先级,负数不会返回字符串)
(-2.34).toFixed(1);  // 返回 "-2.3" (若用括号提高优先级,则返回字符串)

数学对象(Math)

和Number相关的是,JavaScript对象中内置的Math对象,提供了很多数学常数和函数的属性和方法。

属性列表:

属性 描述
Math.E 欧拉常数,也是自然对数的底数, 约等于 2.718
Math.LN2 2的自然对数, 约等于0.693
Math.LN10 10的自然对数, 约等于 2.303
Math.LOG2E 以2为底E的对数, 约等于 1.443
Math.LOG10E 以10为底E的对数, 约等于 0.434
Math.PI 圆周率,一个圆的周长和直径之比,约等于 3.14159
Math.SQRT2 2的平方根,约等于 1.414
Math.SQRT1_2 1/2的平方根, 约等于 0.707

The trigonometric function sin and other parameters in Math are radians. If it is an angle, you can use it (Math.PI / 180)

##Math.sqrt(x)Returns the square root of xMath.cbrt(x)Return the cube root of x##Math.hypot([x[,y[,…]]] )Math.pow(x,y)min(), max()sin(), cos(), tan()asin(), acos(), atan( ), atan2()sinh(), cosh(), tanh()##asinh(), acosh(), atanh()Inverse hyperbolic trigonometric function; the return value is radians.pow(), exp(), expm1(), log10(), log1p(), log2()Exponential and logarithmic functionsThe above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Cross-domain issues with proxyTable in the vue-cli project
Method Description
Math.abs(x) Returns the absolute value of x
Math.sign( x) Returns the sign function of A pseudo-random number between
Math.floor(x) Returns the value of x rounded up
Math .ceil(x) Returns the value of x rounded up
Math.round(x) Returns the rounded integer.
Math.fround(x) Returns the nearest single-precision floating point representation of the number
Math.trunc (x) Returns the integer part of x, removing the decimal number
Returns the square root of the sum of the squares of its parameters
Returns x raised to the y power
Return the smaller or larger value (respectively) of a comma-separated list of numeric arguments
Standard trigonometric functions; parameters are radians
Inverse trigonometric function; the return value is radians
hyperbolic Trigonometric function; the return value is radians.
Related articles:

express builds query server

Use js custom trim function to delete spaces at both ends

The above is the detailed content of Number type in JS (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

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

mPDF

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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.