How JavaScript converts data into Integers

Source: Internet
Author: User

How JavaScript converts data into Integers

This article mainly introduces how JavaScript converts data into integers. If you need it, refer to it.

JavaScript provides the parseInt method to convert a value to an integer, which is used to convert the string data to "123" or a floating point number of 1.23.

 

The Code is as follows:

ParseInt ("1"); // 1

ParseInt ("1.2"); // 1

ParseInt ("-1.2"); //-1

ParseInt (1.2); // 1

ParseInt (0); // 0

ParseInt ("0"); // 0

 

 

However, this parseInt function is not often valid:

 

The Code is as follows:

ParseInt ('06'); // 6

ParseInt ('08'); // 0 note that the new version of Google has been fixed

ParseInt ("1g"); // 1

ParseInt ("g1"); // NaN

 

 

Therefore, I wrote a function to convert any data into integers.

 

The Code is as follows:

Function toInt (number ){

Return number * 1 | 0 | 0;

}

 

// Test

ToInt ("1"); // 1

ToInt ("1.2"); // 1

ToInt ("-1.2"); //-1

ToInt (1.2); // 1

ToInt (0); // 0

ToInt ("0"); // 0

ToInt (Number. NaN); // 0

ToInt (1/0); // 0

 

Here are some conversion functions written by netizens, which can also be used as a reference to convert data into integers.

The Code is as follows:

Function toInt (number ){

Return number & + number | 0 | 0;

}

 

Note that the valid Integer Range of the preceding two functions in Javascript is-1569325056 ~ 1569325056

 

To express a larger range of values in js, I also wrote a function for reference, as shown below:

 

 

The Code is as follows:

Function toInt (number ){

Return Infinity = number? 0: (number * 1 | 0). toFixed (0) * 1;

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.