numeric conversion of JavaScript

Source: Internet
Author: User

JS has 3 functions to convert non-numeric values into values: Number (), parseint (), and parsefloat ().

Number () can be used for any data type, while the other two functions are specifically used to convert a string to a numeric value. These three functions will return different results for the same input.

The conversion rules for the number () function are as follows:

  • If it is a Boolean value, it is converted to 1 or 0.
  • If it is a number, simply pass in the outgoing.
  • If NULL, 0 is returned.
  • If it is undefined, return nan.
  • If it is a string, if the string contains non-numeric characters, it is converted to Nan.
  • If it is an object, call the object's valueof (), then return the value according to the preceding rule, if the conversion result is Nan, call the object's ToString () method, and then convert the returned string value again according to the previous rule.

Because the number () function is more complex and unreasonable when converting strings, parseint () is more commonly used when working with integers. It is more to see if it conforms to the numeric pattern when converting a string. It ignores the spaces in front of the string until the first non-whitespace character is found. If the first character is not a numeric character or symbol, parseint () returns Nan, that is, converting an empty string with parseint () also returns Nan. If the first character is a numeric character, it continues to parse the second character until all subsequent characters have been resolved or the first non-numeric character is encountered. For example, "100px" will be converted to 100. "22.5" is converted to 22 because the decimal point is not a valid numeric character.

Parsefloat is almost the same as parseint, except that it can parse decimals.

numeric conversion of JavaScript

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.