1

JS 大数溢出问题

 11 months ago
source link: https://www.v2ex.com/t/983013
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JS 大数溢出问题

后端的大数到 JS 端 JSON.parse 之后,经常大数溢出。

这个问题之前一直是在后端看到一处,就 stringify 一处。现在实在是觉得烦了,想请教下各位有什么更好的做法?

查了些资料,这个溢出是在 JS 进程里 JSON.parse 的时候发生的,跟 JS 自身有关系,跟 JSON 没有关系。想着,在 JSON.parse 的时候,换成 BigInt 的 JSON.parse 。但是这其中也有两种策略:

1. 只要是整数,全部转成 BigInt ,不管实际会不会溢出。这样的好处是统一,坏处怕会有什么性能问题
2. 只有当一个整数会溢出的时候,才会转成 BigInt 。但是这样用的时候还需要做下判断,比较麻烦。

暂时想在内部后台系统里尝试下,浏览器兼容不成问题。有没有别的高招?

PS. 这个真是 JS 的天坑。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK