Javascript显示非常大的数字,而不是显示xe + n [英] Javascript display really big numbers rather than displaying xe+n

查看:84
本文介绍了Javascript显示非常大的数字,而不是显示xe + n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有javascript代码经常输出非常大的数字,我希望完全显示而不是获得一个值,如 2.7934087356437704e + 56 我想要它显示整个数字。是否有可能在JS中实现这一点?

I have javascript code that often outputs very big numbers, that I would like to be displayed fully rather than getting a value such as 2.7934087356437704e+56 I'd like it to display the entire number. Is it possible to make this happen in JS?

推荐答案

如此庞大的数字,您将失去Javascript的精确度。它返回的指数形式是Javascript可以表示的最精确的形式。但是,如果您不关心精度的损失并且只想要扩展数字的字符串,则可以使用自己的函数来执行此操作。我找不到一个本地执行此操作的方法,因此您必须自己添加它。

With such a large number, you will lose precision in Javascript. The exponential form it returns is the most precise Javascript can represent. However, if you do not care about the loss of precision and just want a string of the expanded number, you can use your own function to do this. I couldn't find a method that will do this natively so you have to add it in yourself.

我发现这个代码片段将通过 Jonas Raoni Soares Silva

I found this snippet which will do that for you by Jonas Raoni Soares Silva:

String.prototype.expandExponential = function(){
    return this.replace(/^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/, function(x, s, n, f, c){
        var l = +c < 0, i = n.length + +c, x = (l ? n : f).length,
        c = ((c = Math.abs(c)) >= x ? c - x + l : 0),
        z = (new Array(c + 1)).join("0"), r = n + f;
        return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : "");
    });
};

用法示例如下:

> var bignum = 2.7934087356437704e+56;
> (bignum+'').expandExponential();
"279340873564377040000000000000000000000000000000000000000"

您必须先将数字转换为字符串,因此 +''

You have to cast the number to a string first, hence the +''

如果你真的需要精确的精度,你可以尝试使用像 Big Number javascript-bignum

If you really need exact precision you can try using a library like Big Number or javascript-bignum.

这篇关于Javascript显示非常大的数字,而不是显示xe + n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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