How to convert data to integer in javascript
Javascript method to convert integers: 1. Use the parseInt() function, the syntax is "parseInt("value to be converted")". 2. Use bit operators, such as "~~123.45". 3. Use the "Math.floor(value)" and "Math.ceil(value)" syntax.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: parseInt() function
parseInt() is a global method that converts values to integers. The conversion process is as follows:
First parse the character at position 0. If it is not a valid number, NaN will be returned directly.
If the character at position 0 is a number or can be converted to a valid number, continue to parse the character at position 1. If it is not a valid number, return the valid character at position 0 directly. number.
And so on, analyzing each character one by one from left to right until a non-numeric character is found.
parseInt() will convert all previously analyzed legal numeric characters into numerical values and return them.
console.log(parseInt("123abc")); //返回数字123 console.log(parseInt("1.73")); //返回数字1 console.log(parseInt(".123")); //返回值NaN
Dots in floating-point numbers are illegal characters for parseInt(), so the decimal part of the value will not be converted.
If it is a numeric string starting with 0, parseInt() will treat it as an octal number: first convert it to an octal value, and then convert it to a decimal number and return it.
If it is a numeric string starting with 0x, parseInt() will treat it as a hexadecimal number: first convert it to a hexadecimal value, and then convert it to a decimal number and return .
var d = 010; //八进制数字字符串 var e = 0x10; //十六进制数字字符串 console.log(parseInt(d)); //返回十进制数字8 console.log(parseInt(e)); //返回十进制数字16
parseInt() also supports base mode, which can convert digital strings in different bases such as binary, octal, and hexadecimal into integers. The base mode is specified by the second parameter of the parseInt() function.
Example 1
The following code converts the hexadecimal digit string "123abc" into a decimal integer.
var a = "123abc"; console.log(parseInt(a,16)); //返回十进制整数1194684
Example 2
The following code converts binary, octal and decimal digit strings into decimal integers.
console.log(parseInt("10",2)); //把二进制数字 10 转换为十进制整数,为 2 console.log(parseInt("10",8)); //把八进制数字 10 转换为十进制整数,为 8 console.log(parseInt("10",10)); //把十进制数字 10 转换为十进制整数,为 10
Example 3
If the first parameter is a decimal value and contains a 0 prefix, in order to avoid being misunderstood as an octal number, the second parameter should be specified The parameter value is 10, which means the base mode is explicitly defined instead of the default base mode.
console.log(parseInt("010")); //把默认基模式数字 010 转换为十进制整数为 10 console.log(parseInt("010",8)); //把八进制数字 010 转换为十进制整数为 8 console.log(parseInt("010",10)); //把十进制数字 010 转换为十进制整数为 10
Method 2: Bit operators
console.log(0 | "123.45")//123 console.log(0 | 123.45)//123 console.log(0 ^ 123.45)//123 console.log(~~123.45)//123
Principle: JavaScript has no concept of integers, and all numerical types are double-precision floating point numbers . When using bitwise operators, they will first convert the operands into integers to facilitate operations. However, XOR or bitwise OR between 0 and other values will not change the operation value
Method 3: Math.floor and Math.ceil
Example
console.log(Math.floor(2.3))//2 console.log(Math.floor(-2.3))//-3 console.log(Math.ceil(2.3))//3 console.log(Math.ceil(-2.3))//-2
The two are insufficient:
Math.floor gets the smallest integer of the number; while Math.ceil gets the largest integer. Therefore, if we round up -2.3, we will get -2, but using Math.floor we will get -3. And 2.3 uses Math.ceil to get 3, but what we want is 2.
Solution:
//自行定义一个函数 function getInt(val){ return val>0 ? Math.floor(val):Math.ceil(val); }
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to convert data to integer in javascript. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

This article will explain in detail the PHP floating point number rounding method. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Floating Point Rounding Overview Floating point numbers are represented in computers as a decimal point followed by an exponent, however, they are often stored in approximations with a limited number of digits. When you need to round a floating point number to a specific precision, there are several ways to do it. Method 1. round() function The round() function rounds a floating point number to the nearest integer. It accepts floating point numbers and optional precision parameters. For example: $num=1.55;echoround($num);//Output: 2echoround($num,1)

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Installing an SSL certificate on SharePoint is a critical step in securing your website and providing an encrypted connection. By following the correct installation steps, you can ensure the security of your website data, improve your ranking in search engines, and provide a better user experience for your visitors. Get an SSL Certificate Contact a trusted Certificate Authority (CA) to purchase an SSL certificate. Provide the required authentication and domain ownership verification information. After completing the verification process, you will receive the SSL certificate file. Prepare the Certificate File Open your SSL certificate file using a text editor. Copy the certificate contents to a new text file. Save the file as yourdomain.cer, making sure to change "yourdomain”

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
