Javascript advanced programming-ecmascript Basics

Source: Internet
Author: User

 

Convert to numbers

1. parseint ()/parsefloat () can run correctly only when these methods are called for the string type. Nan is returned for other types.

 

2. parseint () converts all the literal numbers into numbers.

VaR inum1 = parseint ("123 blue"); // returns 123

VaR inum2 = parseint ("0xa"); // returns 10 hexadecimal to 10 hexadecimal

VaR inum3 = parseint ("22.5"); // returns 22

VaR inum4 = parseint ("blue"); // returns Nan

 

3. The parseint () method also has the base mode. You can convert binary, octal, hexadecimal, or other hexadecimal strings into integers.

If the decimal contains the leading 0, it is best to use base 10 to avoid unexpected octal values.

Eg: var inum1 = parseint ("010"); // returns 8

VaR inum2 = parseint ("010", 8); // returns 8

VaR inum3 = parseint ("010", 10); // return 10

 

4. Another difference in the parsefloat () method is that a string must represent a floating point in decimal format, rather than octal or hexadecimal format. This method willIgnore leading 0So Gossip 0908 will be resolved to 908. Corresponding to the hexadecimal number 0xa, this method returns Nan because X is not a valid character in the floating point number. In addition, parsefloat () does not have a base mode.

 

5. The parseint () and parsefloat () methods only convert strings before the first invalid character. Therefore, "4.5.6" is converted to "4.5 ".Use number () for forced type conversion, Nan.

 

6. The number class also has several special methods for processing numerical values.

A. The tofixed () method returns a string with a specified number. This method is useful when processing currencies. This method can indicate numbers with 0 to 20 decimal places. An error occurs if the number exceeds the limit.

Eg: var onumberobject = new number (99 );

Alert (onumberobject. tofixed (2); // returns "99.00"

B. The toexponential () method returns a string of numbers represented by scientific notation.

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.