为什么parseInt()没有正确转换我的数字串? [英] Why is parseInt() not converting my String of numbers correctly?

查看:805
本文介绍了为什么parseInt()没有正确转换我的数字串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数中有一些逻辑,它接受一串称为数字的数字,如下所示:

I have some logic within a function that takes a string of numbers called digits like so:

6145390195186705543

然后尝试使用parseInt()进行转换:

I then attempt to convert with parseInt() like so:

parseInt(digits)

parseInt(digits)

结果:

digits = parseInt(digits);


6145390195186705000

6145390195186705000

有人能帮我理解为什么会这样吗?以及如何获得准确的转换?

Can someone help me understand why this is the case? and how i can get an accurate conversion?

推荐答案

这是破碎的浮点数学:Javascript使用64位来存储小到原子大小的数字,直到原子数为止宇宙由于这是一个相当宽的范围,它无法准确存储,因此数字以不精确的方式存储,但可以代表非常广泛的范围。在您的情况下 6145390195186705000 是JS能够存储的不准确版本,因为 6145390195186705543 无法存储。

This is another version of "broken" floating point math: Javascript uses 64 bits to store numbers as small as the size of an atom up to the number of atoms in the universe. As that is quite a broad range it cannot be stored accurately, therefore the numbers are stored in an imprecise way but can represent a very broad range. In your case 6145390195186705000 is the inaccurate version JS is able to store as 6145390195186705543 cannot be stored.


以及我如何获得准确的转换?

and how i can get an accurate conversion?

您无法存储准确数字,因此无法准确转换。但是,有些库允许您使用字符串,就像它们是数字一样,例如 BigIntJS

You cannot store an "accurate number", therefore you cannot convert it accurately. However there are some libraries that allow you to work with strings as if they were numbers, such as BigIntJS.

由于这是一个常见问题,这将在下一个JS版本中解决,请参阅提案。您现在可以在新版本的chrome中测试它。

As this is a common problem, this is going to be solved in the next JS version, see this proposal. You can currently test it in the new version of chrome.

这篇关于为什么parseInt()没有正确转换我的数字串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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