The way JavaScript converts data to integers

Source: Internet
Author: User
Tags numeric value valid

  This article mainly introduces the way JavaScript converts data into integers, and friends who need it can refer to the

JavaScript provides a way to convert a numeric value to an integer, parseint the string data "123", or floating-point number 1.23.     Code as follows: parseint ("1");  //1 parseint ("1.2");  //1 parseint ("-1.2");  //-1 parseint (1.2);  //1 parseint (0);  //0 parseint ("0");  //0     But this parseint function is not always valid:   code is as follows: parseint (' 06 '); 6 parseint (' 08 '); 0   Note that Google has revised the new version of parseint ("1g"); 1 parseint ("G1"); NaN     For this reason, I wrote a function to convert arbitrary data into integers.   Code 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 also has the user writes the transformation function, also notes down provides the reference, equally is suitable transforms the data to the integer. The code is as follows: function ToInt (number) {    return number && + number | 0 | | 0;   Note that the above two function JS can represent an integer valid range of -1569325056 ~ 1569325056   In order to express a larger range of values in JS, I also wrote a function to provide reference, as follows:       Code is as follows: function ToInt (number) {    return Infinity = = number? 0: (number*1 | | 0). toFixed (0) *1; }  
Related Article

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.