`
tory320
  • 浏览: 33107 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

javascript converting strings to numbers

阅读更多
To allow more flexible conversions, you can use parseInt( ) and parseFloat( ). These functions convert and return any number at the beginning of a string, ignoring any trailing non-numbers. parseInt( ) parses only integers, while parseFloat( ) parses both integers and floating-point numbers. If a string begins with "0x" or "0X", parseInt( ) interprets it as a hexadecimal number.[4] For example:

[4] The ECMAScript specification says that if a string begins with "0" (but not "0x" or "0X"), parseInt( ) may parse it as an octal number or as a decimal number. Because the behavior is unspecified, you should never use parseInt( ) to parse numbers with leading zeros, unless you explicitly specify the radix to be used!

parseInt("3 blind mice");    // Returns 3

parseFloat("3.14 meters");   // Returns 3.14

parseInt("12.34");           // Returns 12

parseInt("0xFF");            // Returns 255 

parseInt( ) can even take a second argument specifying the radix (base) of the number to be parsed. Legal values are between 2 and 36. For example:

parseInt("11", 2);           // Returns 3 (1*2 + 1)

parseInt("ff", 16);          // Returns 255 (15*16 + 15)

parseInt("zz", 36);          // Returns 1295 (35*36 + 35)

parseInt("077", 8);          // Returns 63 (7*8 + 7)

parseInt("077", 10);         // Returns 77 (7*10 + 7) 

If parseInt( ) or parseFloat( ) cannot convert the specified string to a number, it returns NaN:
parseInt("eleven");          // Returns NaN

parseFloat("$72.47");        // Returns NaN
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics