为什么将非常大的数字解析为整数返回1 [英] Why parsing a very large number to integer return 1

查看:68
本文介绍了为什么将非常大的数字解析为整数返回1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

parseInt(123123123123123123123123);      //return 1
parseInt(123123123123123123123123123);   //return 1
parseInt(123123123123123123123123123123);//return 1

测试在chrome!

推荐答案

parseInt() 为此提供了答案。这是正在发生的事情:

A little creative reading of the documentation for parseInt() provides an answer for this. Here's what's happening:


  1. parseInt 期望它的第一个参数是串。如果不是,则将其转换为字符串。这实际上是搞笑的,因为它似乎通过...将它包装在引号中并通过 .toString()传递,这或多或少与 parseInt()在这种情况下。在您的示例中, parseInt(123123123123123123123123); 变为 parseInt(1.2312312312312312e + 29)

  1. parseInt expects its first argument to be a string. If it isn't, it converts it to a string. This is actually hilarious, because it appears to do that by...wrapping it in quotes and passing it through .toString(), which is more or less the converse of parseInt() in this case. In your example, parseInt(123123123123123123123123); becomes parseInt("1.2312312312312312e+29").

然后它转换为字符串值并通过 parseInt()传递。正如文档告诉我们的那样,如果它遇到一个非数字字符,它就会中止并继续它到目前为止所做的...并且它会截断为一个整数。所以它采取1.2312312312312312e + 29,达到+,中止,解析1.2312312312312312而不是1。

THEN it takes the converted-to-string value and passes it through parseInt(). As the documentation tells us, if it encounters a non-numeric character, it aborts and goes with what it has so far...and it truncates to an integer. So it's taking "1.2312312312312312e+29", reaching the +, aborting, parsing "1.2312312312312312" instead, and coming up with 1.

意想不到的后果!

你只能看到这个问题,其中的int足够大,当转换为字符串时,它们以指数表示法呈现。根本问题是,即使你认为 parseInt() Number.toString()会相互镜像...他们不是,因为通过 toString()传递的int值可以生成 parseInt()不明白。

You'll only see this problem with ints large enough that when converted to strings, they render in exponential notation. The underlying problem is that even though you'd think parseInt() and Number.toString() would mirror each other...they don't, quite, because int values passed through toString() can generate strings that parseInt() doesn't understand.

这篇关于为什么将非常大的数字解析为整数返回1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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