javascript converting strings to numbers

To allow more flexible conversions, you can use parseInt( ) and parseFloat( ). These functions convert and return any number [color=red]at the beginning of a string[/color], 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值