Search code examples
javascriptbigintegerbigdecimaldouble-precision

Converting/expressing double number in non-exponent/short form in Javascript


I have a double in Javascript whose value is, for example, 1.0883076389305e-311. I want to express it in the following form, using as example the 'bc' utility to calculate the expanded/higher precision/scale form:

$ bc
scale=400
1.0883076389305000*10^-311
.0000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000010883076389305000000000000000\
0000000000000000000000000000000000000000000000000000000000000

I need a Javascript bigint library or code to produce the same output as a string with the expanded/higher precision form of the number.

Thanks!


Solution

  • This is horrible, but works with every test case I can think of:

    Number.prototype.toFullFixed = function() {
        var s = Math.abs(this).toExponential();
        var a = s.split('e');
        var f = a[0].replace('.', '');
        var d = f.length;
        var e = parseInt(a[1], 10);
        var n = Math.abs(e);
    
        if (e >= 0) {
            n = n - d + 1;
        }
    
        var z = '';
        for (var i = 0; i < n; ++i) {
            z += '0';
        }
    
        if (e <= 0) {
            f = z + f;
            f = f.substring(0, 1) + '.' + f.substring(1);
        } else {
            f = f + z;
            if (n < 0) {
                f = f.substring(0, e + 1) + '.' + f.substring(e + 1);
            }
        }
    
        if (this < 0) {
            f = '-' + f;
        }
    
        return f;
    };
    

    If you find a number that doesn't parse back correctly, i.e. n !== parseFloat(n.toFullFixed()), please let me know what it is!