最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

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
Share Improve this question edited Apr 22, 2013 at 4:34 arjunaskykok asked Apr 22, 2013 at 4:27 arjunaskykokarjunaskykok 9561 gold badge11 silver badges17 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17

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"

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

You can use from-exponential module. It is lightweight and fully tested.

It accepts strings and numbers so it will not lose precision during conversion.

import fromExponential from 'from-exponential';

fromExponential('1.12345678901234567890e-10'); 
// '0.00000000011234567890123456789'
发布评论

评论列表(0)

  1. 暂无评论