Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert big negative scientific notation number into decimal notation string in javascript?

Tags:

javascript

converter_scientific_notation_to_decimal_notation('1.34E-15') or converter_scientific_notation_to_decimal_notation(1.34E-15)

=> '0.00000000000000134'

converter_scientific_notation_to_decimal_notation('2.54E-20') or converter_scientific_notation_to_decimal_notation(2.54E-20)

=> '0.000000000000000000254'

Does such function exist in Javascript?

parseFloat is not good for big negative scientific number.

parseFloat('1.34E-5') => 0.0000134
parseFloat('1.34E-15') => 1.34e-15
like image 618
arjunaskykok Avatar asked Apr 22 '13 04:04

arjunaskykok


Video Answer


2 Answers

This works for any positive or negative number with the exponential 'E', positive or negative. (You can convert a numerical string to a number by prefixing '+', or make it a string method, or a method of any object, and call the string or number.)

Number.prototype.noExponents= function(){
    var data= String(this).split(/[eE]/);
    if(data.length== 1) return data[0]; 

    var  z= '', sign= this<0? '-':'',
    str= data[0].replace('.', ''),
    mag= Number(data[1])+ 1;

    if(mag<0){
        z= sign + '0.';
        while(mag++) z += '0';
        return z + str.replace(/^\-/,'');
    }
    mag -= str.length;  
    while(mag--) z += '0';
    return str + z;
}

var n=2.54E-20;
n.noExponents();

returned value:

"0.0000000000000000000254"
like image 130
kennebec Avatar answered Sep 18 '22 11:09

kennebec


You can use toFixed: (1.34E-15).toFixed(18) returns 0.000000000000001340

like image 43
Mimo Avatar answered Sep 18 '22 11:09

Mimo