在JavaScript中将指数转换为整数

编程入门 行业动态 更新时间:2024-10-24 18:22:12
本文介绍了在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中将指数转换为整数

本文发布于:2023-10-24 16:53:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524490.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   指数   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!