parseInt和Radix

Everyone knows that the parseInt function within JavaScript turns your decimal number or string into a rounded integer.  parseInt turns 10.937 into 10, 0.2 into 0, and "someValue" into NaN.  If you use parseInt without a radix, however, you'll receive a warning that no radix has been provided.  In most cases, the radix you want to use is 10:

每个人都知道JavaScript中的parseInt函数会将您的十进制数字或字符串转换为四舍五入的整数。 parseInt将10.937转换为10,将0.2转换为0,将“ someValue”转换为NaN 。 但是,如果使用不带基数的parseInt ,则会收到一条警告,提示您未提供基数。 在大多数情况下,您要使用的基数为10:


parseInt(10.83, 10); // 10, no warning
parseInt(.83, 10); // 0, no warning

parseInt(0.8); // 8, unintended result
parseInt(0.8, 10); // 0, intended result


Using a 10 radix means the number is parsed with a base 10 and thus turns the number into the integer you're expecting, without the annoying warning.  The radix is important if you're need to guarantee accuracy with variable input (basic number, binary, etc.).  For best results, always use a radix of 10!

使用10的基数意味着该数字将以10为底进行解析,从而将数字转换为您期望的整数,而不会产生讨厌的警告。 如果您需要保证变量输入(基本数,二进制数等)的准确性,则基数很重要。 为了获得最佳结果,请始终使用10的基数!

翻译自: https://davidwalsh.name/parseint-radix

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值