parseInt()用指数错误地解析数字文字 [英] parseInt() parses number literals with exponent incorrectly

查看:88
本文介绍了parseInt()用指数错误地解析数字文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚观察到 parseInt 函数在整数的情况下不会处理小数(包含 e 字符)。

I have just observed that the parseInt function doesn't take care about the decimals in case of integers (numbers containing the e character).

我们举个例子: -3.67394039744206e-15

> parseInt(-3.67394039744206e-15)
-3
> -3.67394039744206e-15.toFixed(19)
-3.6739e-15
> -3.67394039744206e-15.toFixed(2)
-0
> Math.round(-3.67394039744206e-15)
0

我预计 parseInt 也会返回 0 。在较低级别发生了什么?为什么 parseInt 在这种情况下返回 3 (会不会感谢源代码中的一些片段)?

I expected that the parseInt will also return 0. What's going on at lower level? Why does parseInt return 3 in this case (some snippets from the source code would be appreciated)?

在这个例子中,我使用的是 node v0.12.1 ,但我希望在浏览器和其他JavaScript引擎中也能这样。 / p>

In this example I'm using node v0.12.1, but I expect same to happen in browser and other JavaScript engines.

推荐答案

我认为原因是 parseInt 通过调用 ToString 将返回 - 3.67394039744206e-15,然后解析它以便它将考虑 -3 并将其返回。

I think the reason is parseInt converts the passed value to string by calling ToString which will return "-3.67394039744206e-15", then parses it so it will consider -3 and will return it.

mdn documentation


parseInt函数将其第一个参数转换为字符串,解析
it,并返回一个整数或NaN

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN

这篇关于parseInt()用指数错误地解析数字文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆