search
HomeWeb Front-endJS TutorialIntroduction to Number object in JavaScript (code example)

This article brings you an introduction to the Number object in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Create Number instance object

    /**
     * new Number(value);
     * value  被创建对象的数字值
     *
     * Number 对象主要用于:
        如果参数无法被转换为数字,则返回 NaN。
        在非构造器上下文中 (如:没有 new 操作符),Number 能被用来执行类型转换
     */
    let number = new Number("1100");
    console.log(number); //Number {1100}
    console.log(Number("123"));     // 123
    console.log(Number(""));        // 0
    console.log(Number("0x11"));    // 17
    console.log(Number("0b11"));    // 3
    console.log(Number("0o11"));    // 9
    console.log(Number("foo"));     // NaN
    console.log(Number("100a"));    // NaN

2. Number static property

1.Number.EPSILON property

represents the difference between 1 and the minimum value greater than 1 (can be expressed as Number). The value of the EPSILON attribute is close to 2.2204460492503130808472633361816E-16, or 2^(-52)

    let x = 0.2;
    let y = 0.3;
    let z = 0.1;
    let equal = (Math.abs(x - y + z) <p>2.Number .MAX_SAFE_INTEGER attribute</p><p>Constant represents the maximum safe integer (maxinum safe integer) in JavaScript (2^53 - 1)</p><p>3.Number.MAX_VALUE attribute</p><p>Represents the The maximum value that can be represented in JavaScript is close to 1.79E 308. Values ​​greater than MAX_VALUE represent "Infinity"</p><p>4.Number.MIN_SAFE_INTEGER attribute</p><p> represents the smallest safe integer in JavaScript Type number (-(2^53 - 1))</p><p>5.Number.MIN_VALUE attribute</p><p> represents the smallest positive value that can be expressed in JavaScript, the value is approximately 5e-324, Values ​​less than MIN_VALUE ("underflow values") will be converted to 0</p><p>6.Number.NEGATIVE_INFINITY property</p><p>represents negative infinity, and its value is the same as the negative value of the Infinity property of the global object</p><p>7.Number.NaN attribute</p><p> means "Not-A-Number", which is the same as the global NaN</p><p>8.Number.POSITIVE_INFINITY attribute</p> <p>Represents positive infinity, its value is the same as the value of the global object Infinity property </p><p>9.Number.prototype property </p><p>Represents the prototype of the Number constructor, and all Number instances inherit from Number. prototype, modifying the prototype object of the Number constructor will affect all Number instances</p><p><strong>3. Number static method</strong></p><p>1.Number.isFinite() method is used to detect the passed Whether the input parameter is a finite number</p><pre class="brush:php;toolbar:false">    /**
     * Number.isFinite() 方法用来检测传入的参数是否是一个有穷数(finite number)
     * Number.isFinite(value)
     * value   要被检测有穷性的值
     *
     * 和全局的 isFinite() 函数相比,这个方法不会强制将一个非数值的参数转换成数值,这就意味着,只有数值类型的值,且是有穷的(finite),才返回 true
     * 返回值:一个 布尔值 表示给定的值是否是一个有穷数
     */
    console.log(Number.isFinite(Infinity));  // false
    console.log(Number.isFinite(NaN));       // false
    console.log(Number.isFinite(-Infinity)); // false
    console.log(Number.isFinite(0));         // true
    console.log(Number.isFinite(2e64));      // true
    console.log(Number.isFinite('0'));       // false, 全局函数 isFinite('0') 会返回 true

2.Number.isInteger() method is used to determine whether the given parameter is an integer

    /**
     * Number.isInteger() 方法用来判断给定的参数是否为整数
     * Number.isInteger(value)
     * value   要判断此参数是否为整数
     *
     * 如果被检测的值是整数,则返回 true,否则返回 false。注意 NaN 和正负 Infinity 不是整数
     * 返回值:判断给定值是否是整数的 Boolean 值
     */
    console.log(Number.isInteger(0));         // true
    console.log(Number.isInteger(1));         // true
    console.log(Number.isInteger(-100000));   // true
    console.log(Number.isInteger(0.1));       // false
    console.log(Number.isInteger(Math.PI));   // false
    console.log(Number.isInteger(Infinity));  // false
    console.log(Number.isInteger(-Infinity)); // false
    console.log(Number.isInteger("10"));      // false
    console.log(Number.isInteger(true));      // false
    console.log(Number.isInteger(false));     // false
    console.log(Number.isInteger([1]));       // false

3.Number.isNaN() method determines Whether the passed value is NaN and its type is Number

    /**
     * Number.isNaN() 方法确定传递的值是否为 NaN和其类型是 Number。它是原始的全局isNaN()的更强大的版本
     * Number.isNaN(value)
     * value  要被检测是否是 NaN 的值
     *
     * NaN 最特殊的地方就是,我们不能使用相等运算符(== 和 ===)来判断一个值是否是 NaN,因为 NaN == NaN 和 NaN === NaN 都会返回 false
     * 返回值:一个布尔值,表示给定的值是否是 NaN
     */
    console.log(NaN == NaN); //false
    console.log(NaN === NaN); //false
    console.log(Number.isNaN(NaN));        // true
    console.log(Number.isNaN(Number.NaN)); // true
    console.log(Number.isNaN(0 / 0));     // true

// 下面这几个如果使用全局的 isNaN() 时,会返回 true。
    console.log(Number.isNaN("NaN"));      // false,字符串 "NaN" 不会被隐式转换成数字 NaN。
    console.log(Number.isNaN(undefined));  // false
    console.log(Number.isNaN({}));         // false
    console.log(Number.isNaN("blabla"));   // false
    console.log(isNaN("NaN"));      // true
    console.log(isNaN(undefined));  // true
    console.log(isNaN({}));         // true
    console.log(isNaN("blabla"));   // true

4.Number.isSafeInteger() method is used to determine whether the passed parameter value is a "safe integer" (safe integer)

    /**
     * Number.isSafeInteger() 方法用来判断传入的参数值是否是一个“安全整数”(safe integer)
     * Number.isSafeInteger(testValue)
     * testValue   需要检测的参数
     *
     * 返回值:一个布尔值 表示给定的值是否是一个安全整数(safe integer)
     */
    console.log(Number.isSafeInteger(3));                    // true
    console.log(Number.isSafeInteger(Math.pow(2, 53)));       // false
    console.log(Number.isSafeInteger(Math.pow(2, 53) - 1));   // true
    console.log(Number.isSafeInteger(NaN));                  // false
    console.log(Number.isSafeInteger(Infinity));             // false
    console.log(Number.isSafeInteger("3"));                  // false
    console.log(Number.isSafeInteger(3.1));                  // false
    console.log(Number.isSafeInteger(3.0));                  // true

5.Number.parseFloat() method can parse a string into a floating point number. This method is the same as the global parseFloat() function

    /**
     * Number.parseFloat() 方法可以把一个字符串解析成浮点数。该方法与全局的 parseFloat() 函数相同
     * Number.parseFloat(string)
     * string 被解析的字符串
     */
    console.log(Number.parseFloat("3.14")); //3.14
    console.log(Number.parseFloat("314e-2")); //3.14
    console.log(Number.parseFloat("0.0314E+2")); //3.14
    console.log(Number.parseFloat("3.14more non-digit characters")); //3.14

6.Number.parseInt() method can parse a string into an integer based on the given base number. This method is the same as the global parseInt() function

    /**
     * Number.parseInt() 方法可以根据给定的进制数把一个字符串解析成整数。该方法和全局的 parseInt() 函数相同
     * Number.parseInt(string[, radix])
     * string   要被解析的值。
        如果参数不是一个字符串,则将其转换为字符串(使用  ToString 抽象操作),字符串开头的空白符将会被忽略
     * radix   一个介于2和36之间的整数,表示上述字符串的基数
        比如参数"10"表示使用我们通常使用的十进制数值系统
        当未指定基数时,不同的实现会产生不同的结果,通常将值默认为10
     *
     * 返回值:返回解析后的整数值。如果被解析参数的第一个字符无法被转化成数值类型,则返回 NaN
     */
    console.log(Number.parseInt("015", 10)); //15
    console.log(Number.parseInt("0xF", 16)); //15
    console.log(Number.parseInt('017', 8)); //15
    console.log(Number.parseInt("1111", 2)); //15
    console.log(Number.parseInt(15.99, 10)); //15

4. Number instance method

1.toExponential() method returns the numerical string representation in exponential notation Form

    /**
     * toExponential() 方法以指数表示法返回该数值字符串表示形式
     * numObj.toExponential(fractionDigits)
     *
     * fractionDigits  可选,一个整数,用来指定小数点后有几位数字。默认情况下用尽可能多的位数来显示数字
     * 返回值:一个用幂的形式 (科学记数法) 来表示Number 对象的字符串
     */
    let number1 = 777.1234;
    console.log(number1.toExponential()); //输出 7.771234e+2
    console.log(number1.toExponential(4)); //输出 7.7712e+2
    console.log(number1.toExponential(2)); //输出 7.77e+2

2.toFixed() method uses fixed-point representation to format a number

    /**
     * toFixed() 方法使用定点表示法来格式化一个数
     * numObj.toFixed(digits)
     *
     * digits  小数点后数字的个数;介于0到20(包括)之间,实现环境可能支持更大范围。如果忽略该参数,则默认为 0
     *
     * 返回值:所给数值的定点数表示法的字符串形式
     */
    let number2 = 12345.6789;
    console.log(number2.toFixed());      // 返回 "12346":进行四舍五入,不包括小数部分
    console.log(number2.toFixed(1));     // 返回 "12345.7":进行四舍五入
    console.log(number2.toFixed(6));     // 返回 "12345.678900":用0填充
    console.log(-2.34.toFixed(1));         // 返回 -2.3 (由于操作符优先级,负数不会返回字符串)
    console.log((-2.34).toFixed(1));       // 返回 "-2.3" (若用括号提高优先级,则返回字符串)

3.toPrecision() method returns a string representation of the numeric object with the specified precision

    /**
     * toPrecision() 方法以指定的精度返回该数值对象的字符串表示
     * numObj.toPrecision(precision)
     *
     * precision  可选。一个用来指定有效数个数的整数
     *
     * 返回值:以定点表示法或指数表示法表示的一个数值对象的字符串表示,四舍五入到 precision 参数指定的显示数字位数
     */
    let number3 = 5.123456;
    console.log(number3.toPrecision());  //输出 5.123456
    console.log(number3.toPrecision(5)); //输出 5.1235
    console.log(number3.toPrecision(2)); //输出 5.1
    console.log(number3.toPrecision(1)); //输出 5

// 注意:在某些情况下会以指数表示法返回
    console.log((1234.5).toPrecision(2)); // "1.2e+3"

4.toString() method returns the string representation of the specified Number object

    /**
     * toString() 方法返回指定 Number 对象的字符串表示形式
     * numObj.toString([radix])
     *
     * radix  指定要用于数字到字符串的转换的基数(从2到36)。如果未指定 radix 参数,则默认值为 10
     */
    let count = 10;
    console.log(count.toString());    // 输出 '10'
    console.log((17).toString());     // 输出 '17'
    console.log((17.2).toString());   // 输出 '17.2'
    let x = 6;
    console.log(x.toString(2));       // 输出 '110'
    console.log((254).toString(16));  // 输出 'fe'
    console.log((-10).toString(2));   // 输出 '-1010'
    console.log((-0xff).toString(2)); // 输出 '-11111111'

5.valueOf() method returns a primitive value wrapped by a Number object

    /**
     * valueOf() 方法返回一个被 Number 对象包装的原始值
     * numObj.valueOf()
     *
     * 返回值:表示指定 Number 对象的原始值的数字
     */
    let number4 = new Number(10);
    console.log(typeof number4);  // object
    let num = number4.valueOf();
    console.log(num);            // 10
    console.log(typeof num);    // number

The above is the detailed content of Introduction to Number object in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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.

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
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor