【问题标题】:How to work with big numbers (int64 / bigInt) in Google App Script?如何在 Google App Script 中使用大数字(int64 / bigInt)?
【发布时间】:2020-11-01 06:13:24
【问题描述】:

如下所示,在所有情况下,数字都显示错误:

  var a = 714205074837649919;
  console.log(a); //>> 7.1420507483764992E17
  console.log(parseInt(a)); //>> 7.1420507483764992E17
  console.log(parseInt(a).toString()); //>> 714205074837649900
  console.log(parseFloat(a).toString()); //>> 714205074837649900

【问题讨论】:

标签: javascript google-apps-script bigint int64


【解决方案1】:

Apps Script 全局环境包括BigInt

在为BigInt 对象提供文字时,使用字符串而不是数字来避免舍入错误。

function testBigInt() {
  const bigNumber = BigInt("714205074837649919");
  console.log(bigNumber.toString()); // 714205074837649919
}

【讨论】:

  • 要补充这一点,n 表示法:1n 会引发语法错误:Unexpected token ILLEGAL (line 5075, file "esprima.browser.js-bundle.js") 应该有人在 issuetracker 中发布问题;
  • 你知道为什么它会四舍五入到 7142050748376499'20' 吗?我需要确切的数字 7142050748376499'19'
  • @BrunoYuzo number 和 bigint 之间的转换导致了这种情况。将数字更改为字符串:const bigNumber = BigInt("714205074837649919");
  • 我收到的json值不是字符串,如你所见:var JsonValue = JSON.parse('[{"GroupId":714205074837649919,"Type":"OrganisationGroup"}]'); console.log(JsonValue[0].GroupId); //7.1420507483764992E17
  • @BrunoYuzo 因为您是通过这种方式接收的,所以您可能需要在解析之前使用 RegExp 来修复 JSON。见this relevant stackoverflow question
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多