JavaScript Learning notes: 2 ways to convert strings to numbers

Source: Internet
Author: User

① using Parseint/parsefloat (number.parseint/number.parsefloat in ECMAScript6)

1Console.log (parseint (' A10 '));//NaN2Console.log (parseint (' 1a0 '));//13Console.log (parseint (' 10a '));//Ten4Console.log (parseint (' 10 '));//Ten5 6Console.log (parsefloat (' a10.1 '));//NaN7Console.log (parsefloat (' 1a0.1 '));//18Console.log (parsefloat (' 10a.1 '));//Ten9Console.log (parsefloat (' 10.1a '));//10.1TenConsole.log (parsefloat (' 10.1 '));//10.1

② using the ' + ' operator

1Console.log (+ ' A10 ');//NaN2Console.log (+ ' 1a0 ');//NaN3Console.log (+ ' 10a ');//NaN4Console.log (+ ' 10 ');//Ten5 6Console.log (+ ' a10.1 ');//NaN7Console.log (+ ' 1a0.1 ');//NaN8Console.log (+ ' 10a.1 ');//NaN9Console.log (+ ' 10.1a ');//NaNTenConsole.log (+ ' 10.1 ');//10.1

Although you can convert a string to a number in both ways, the obvious conversion is different. When a string-to-numeric conversion is performed using Parseint/parsefloat, the characters in the string are parsed one after the other until the parsed character ends, and the parsed portion is converted to a numeric return. However, when a string-to-number conversion is performed in this way using the ' + ' operator, it returns Nan directly as long as there are characters in the string that cannot be parsed. This is the difference between the two modes of conversion, please note the distinction.

JavaScript Learning notes: 2 ways to convert strings to numbers

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.