在JavaScript中将指数转换为整数 [英] Convert exponential number to a whole number in javascript

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

问题描述

我需要在网址中使用23位数字.我正在使用Math.random()生成数字,但是得到的是指数形式的结果.

I am in need use 23 digit number in a url. I am generating number using Math.random() but I get the result in exponential form.

我的代码是

var id = (Math.random()*11111111111111111111111).toFixed(23);

但是我得到的结果是6.286119436349295e+21

如何将"id"中的随机值作为整数存储?

how to store random value in "id" as a whole number ?

推荐答案

JavaScript可以连续表示-9007199254740992和9007199254740992之间的整数.实际上,可以表示更大(或更小的)整数,但不是全部其中!实际上,9007199254740992之后的下一个"整数是9007199254740994.它们彼此分开一段时间,然后变成4,然后变成8,以此类推.您已经注意到,当它们变大时,它们会以科学计数法显示.即使toFixed的结果也不能保证以仅由数字组成的形式显示.

JavaScript can represent contiguously the integers between -9007199254740992 and 9007199254740992. It actually can represent larger (and smaller) integers, but not all of them! In fact the "next" integer after 9007199254740992 is 9007199254740994. They are two apart for a while, then become 4 apart, then 8, etc. As you noticed, when they get really large, they display in scientific notation. Even the result of toFixed is not guaranteed to be displayed in a form that consists of digits only.

因此,当您计算23位十进制数字范围内的整数时,将无法使用JavaScript的本机Number类型(IEEE-754 64位)表示一堆整数.

So when you compute integers that would be in the range of 23 decimal digits, you would be unable to represent a bunch of them using JavaScript's native Number type (IEEE-754 64-bit).

如果您不关心随机数的特定分布,则可以在字母0..9上使用随机字符串,也可以将较小的整数粘贴在一起,但是如果您 正在寻找一个特定的发行版,那么您应该(根据Ignacio Vasquez-Abrams的建议)使用支持任意长度精度的库.

If you don't care about a specific distribution for your random numbers, a random string over the alphabet 0..9 can work, as can pasting together smaller integers, but if you are looking for a specific distribution then you should (as suggested by Ignacio Vasquez-Abrams) use a library supporting arbitrary-length precision.

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

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