简体   繁体   English

JavaScript 将科学记数法中的不安全整数转换为字符串

[英]JavaScript convert not safe integer in scientific notation to string

I have one API for generate a random map tileset with a Erlang server, with safe integer JavaScript can request to API good but the problem is when is more than Number.MAX_SAFE_INTEGER .我有一个用于使用 Erlang 服务器生成随机地图Number.MAX_SAFE_INTEGER API,使用安全整数 JavaScript 可以向 API 请求良好但问题是何时超过Number.MAX_SAFE_INTEGER

Then, in the server I haven't the integer becuse JavaScript send 1e+21 number in scientific notation, not 999999999999999999999 and I need the number like string not in scientific notation.然后,在服务器中我没有整数,因为 JavaScript 以科学记数法发送1e+21数字,而不是999999999999999999999 ,我需要像字符串这样的数字,而不是科学记数法。

How can I get a string like "999999999999999999999" in JavaScript for send to API that and not scientific notation string?如何在 JavaScript 中获取像"999999999999999999999"这样的字符串以发送到 API 而不是科学记数法字符串? Exists a library for arbitrary long numbers in JavaScript small only for the number? JavaScript 中是否存在用于任意长数字的库,仅用于数字? The umber is a X and Y number of position and need the correct position, and not is good a big library because need good performance for render the map in ms, is for a game in browser, not for astronomy calc.数字是 X 和 Y 的位置数,需要正确的位置,而不是一个好的大库,因为需要在 ms 中渲染地图的良好性能,用于浏览器中的游戏,而不是用于天文计算。

you could use the BigNumber library ( https://github.com/MikeMcl/bignumber.js/ ).您可以使用 BigNumber 库( https://github.com/MikeMcl/bignumber.js/ )。

These 2 lines should do the trick:这两行应该可以解决问题:

BigNumber.config({EXPONENTIAL_AT: [-10, 30]});
var stringifiedLongNumber = new BigNumber('999999999999999999999').toString();

EXPONENTIAL_AT config parameter documentation: http://mikemcl.github.io/bignumber.js/#exponential-at EXPONENTIAL_AT 配置参数文档: http : //mikemcl.github.io/bignumber.js/#exponential-at

Maybe is better a small solution using optimizations of asm.js and work with strings for add and rest to the number, this a example simple but is possible do better:也许使用 asm.js 优化的小解决方案更好,并使用字符串对数字进行添加和休息,这是一个简单的示例,但可能做得更好:

var a = "999999";
var b = "";
var acarreo = 1|0;
console.log(a);
for(var i=a.length-1|0; i >= 0; i--){
    var j = parseInt(a[i])|0;
    var j = j + acarreo|0;
    if(j > 9){
        j-=10|0;
        acarreo=1|0;
    }else{
        acarreo=0|0;
    }
    b = j.toString() + b;
}
if(acarreo>0){
    a = acarreo.toString() + b;
}else{
    a = b;
}
console.log(a);

在这种情况下,一种可能的解决方案是不向服务器发送新位置,而只发送一个移动事件,然后 Erlang 中的服务器可以计算任意长数字的新位置(同时有足够的内存来处理非常大的数字),并且在 JavaScript 中没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM