Expand Exponential //JavaScript Repository

Description

Expands a number in the exponential form to the decimal form.
Created: 2006.05.08

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/expand-exponential [rev. #1]

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) : "");
    });
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

document.write(
    '"', s = "-13.441e+5", '".expandExponential() = ', s.expandExponential(), '<br />',
    '"', s = "1.12300e-1", '".expandExponential() = ', s.expandExponential(), '<br />',
    "n = ", n = 100000000000000000000000000000000000, " => String(n).expandExponential() = ",
    String(n).expandExponential()
);

//]]>
</script>

Help

String.prototype.expandExponential(void): String
Expands a number in the exponential form to the decimal form.

Rank (Votes: 21)

4.43