与 JS 中的 Number.toExponential 相反
我需要以非指数形式获取 JavaScript 中极大数字的值。 Number.toFixed
只是以指数形式将其返回为字符串,这比我的情况更糟糕。
这就是 Number.toFixed
返回的内容:
>>> x = 1e+31
1e+31
>>> x.toFixed()
"1e+31"
Number.toPrecision
也不起作用:
>>> x = 1e+31
1e+31
>>> x.toPrecision( 21 )
"9.99999999999999963590e+30"
我想要的是:
>>> x = 1e+31
1e+31
>>> x.toNotExponential()
"10000000000000000000000000000000"
我可以编写自己的解析器,但我宁愿使用本机 JS方法(如果存在)。
I need to get the value of an extremely large number in JavaScript in non-exponential form. Number.toFixed
simply returns it in exponential form as a string, which is worse than what I had.
This is what Number.toFixed
returns:
>>> x = 1e+31
1e+31
>>> x.toFixed()
"1e+31"
Number.toPrecision
also does not work:
>>> x = 1e+31
1e+31
>>> x.toPrecision( 21 )
"9.99999999999999963590e+30"
What I would like is:
>>> x = 1e+31
1e+31
>>> x.toNotExponential()
"10000000000000000000000000000000"
I could write my own parser but I would rather use a native JS method if one exists.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
toPrecision
以及指定您要输入多少位数字的参数想要显示:但是,在我测试的浏览器中,上述代码仅适用于Firefox。根据 ECMAScript 规范,
toPrecision
的有效范围是 1 到 21,IE 和 Chrome 都会相应地抛出RangeError
。这是因为 JavaScript 中使用的浮点表示实际上无法将数字表示为 31 位精度。You can use
toPrecision
with a parameter specifying how many digits you want to display:However, among the browsers I tested, the above code only works on Firefox. According to the ECMAScript specification, the valid range for
toPrecision
is 1 to 21, and both IE and Chrome throw aRangeError
accordingly. This is due to the fact that the floating-point representation used in JavaScript is incapable of actually representing numbers to 31 digits of precision.使用
数字(字符串)
示例:
返回:
a = 110
Use
Number(string)
Example :
Return :
a = 110
答案是没有这样的内置函数。我已经从高处和低处寻找过。
这是我用来将数字拆分为符号、系数(小数点前的数字)、小数部分(小数点后的数字)和指数的正则表达式:
“Roll your own”就是答案,您已经这样做了。
The answer is there's no such built-in function. I've searched high and low.
Here's the RegExp I use to split the number into sign, coefficient (digits before decimal point), fractional part (digits after decimal point) and exponent:
"Roll your own" is the answer, which you already did.
可以使用字符串函数扩展 JavaScript 的指数输出。诚然,我的想法有点神秘,但如果
e
后面的指数为正,它就有效:It's possible to expand JavaScript's exponential output using string functions. Admittedly, what I came up is somewhat cryptic, but it works if the exponent after the
e
is positive:“10000000000000000000000000000000”?
很难相信有人更愿意看它而不是 1.0e+31
或 html: 1031。
但这里有一种方法,其中大部分是针对负指数(分数):
"10000000000000000000000000000000"?
Hard to believe that anybody would rather look at that than 1.0e+31,
or in html: 1031.
But here's one way, much of it is for negative exponents(fractions):