与JS中的Number.toExponential相反 [英] Opposite of Number.toExponential in JS

查看:206
本文介绍了与JS中的Number.toExponential相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以非指数形式在JavaScript中获取极大数字的值。 Number.toFixed 只是以指数形式将其作为字符串返回,这比我的更糟。

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.

这是什么 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 could write my own parser but I would rather use a native JS method if one exists.

推荐答案

答案是没有这样的内置函数。我搜索过高低。
这是我用来将数字分成符号,系数(小数点前的数字),小数部分(小数点后的数字)和指数的RegExp:

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:

/^([+-])?(\d+)\.?(\d*)[eE]([+-]?\d+)$/

滚动你自己是你已经做过的答案。

"Roll your own" is the answer, which you already did.

这篇关于与JS中的Number.toExponential相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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