如何在JavaScript中将字符串转换为bigint [英] How to convert strings to bigint in JavaScript

查看:2198
本文介绍了如何在JavaScript中将字符串转换为bigint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Javascript中将字符串转换为bigint,如 BigInteger

I need to convert a string to bigint like BigInteger in Javascript

示例

var reqId = "78099864177253771992779766288266836166272662";
var result = parseInt(reqId);
document.write(result);

结果值不匹配,因为JavaScript允许整数最多为2 ^ 53。

Resultant value not matching since JavaScript allows integers up to 2^53.

有没有办法克服这个问题?

Is there any way to overcome this?

推荐答案

BigInt 现在是原生JavaScript语言功能。它位于TC39流程的第3阶段,它在V8 v6.7和Chrome 67中发布。

BigInt is now a native JavaScript language feature. It's at Stage 3 in the TC39 process and it's shipping in V8 v6.7 and Chrome 67.

将包含有效数字文字的字符串转换为 BigInt ,使用全局 BigInt 函数:

To turn a string containing a valid numeric literal into a BigInt, use the global BigInt function:

const string = '78099864177253771992779766288266836166272662';
BigInt(string);
// 78099864177253771992779766288266836166272662n

如果您只想将数值硬编码到代码中,那么不需要从字符串转换;改为使用 BigInt 字面值:

If you just want to hardcode the numeric value into your code, there is no need to convert from a string; use a BigInt literal instead:

const value = 78099864177253771992779766288266836166272662n;

这篇关于如何在JavaScript中将字符串转换为bigint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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