javascript - parseInt() 和 parseFloat() 之间的行为差​​异

标签 javascript parsing

<分区>

为什么 parseInt()parseFloat() 之间存在这种行为差异?

我有一个包含 08 的字符串。

当我写这段代码时:

alert(hfrom[0]);
alert(parseInt(hfrom[0]));
alert(parseFloat(hfrom[0]));

生成以下输出:

08
0
8

为什么在这种情况下 parseIntparseFloat 返回两个不同的结果?

最佳答案

parseInt()根据字符串中的第一个字符假定您的数字的基数。如果它以 0x 开头,它假定以 16 为底(十六进制)。否则,如果它以 0 开头,则假定基数为 8(八进制)。否则它假定基数为 10。

您可以将基数指定为第二个参数:

alert(parseInt(hfrom[0], 10)); // 8

来自 MDN(上面链接):

If radix is undefined or 0, JavaScript assumes the following:

If the input string begins with "0x" or "0X", radix is 16 (hexadecimal). If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt. If the input string begins with any other value, the radix is 10 (decimal).

关于javascript - parseInt() 和 parseFloat() 之间的行为差​​异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9528433/

相关文章:

javascript - 使用 AJAX POST 请求发送自定义 HTTP 正文

javascript - 如何彻底去除手机浏览器长按震动?

java - 在 Java 中将 HTML 转换为纯文本

c# - 如何比 OpenPop.dll 更快地解析电子邮件

ios - 适用于 iOS 的简单 XML 解析器 - Objective C

javascript - 从同一对象内的另一个函数引用对象内的函数。 JavaScript 对象字面形式

javascript - 如何将 JWT 保存到 localStorage

parsing - 列表成员实例化时约束不会传播

javascript - 我如何用我的数据库值显示图表

java - 我应该从哪里下载什么 jar 文件?