Search code examples
javascriptscientific-notation

What to do when scientific notation exceeds the toPrecision range


I would like to show some numbers on a website which are now in scientific notation. I am using toPrecision to show normal notation for the numbers.

Unfortunately toPrecision only works in the range from 1e-6 to 1e20 and I do have numbers like 1e-7 and 1e-10.

So what can I do when toPrecision doesn't do the job I would like it to do?

I tried using Number() and parseFloat() and even both to try to get this number to be shown in normal notation...

var min =  1e7,
nr1 = parseFloat(Number(min).toPrecision()),
nr2 = Number(min).toPrecision(),
nr3 = min.toPrecision(),
nr4 = min.toString();

console.log(nr1); //1e-7
console.log(nr2); //1e-7
console.log(nr3); //1e-7
console.log(nr4); //1e-7

Nothing worked so far.

Any help will be appreciated


Solution

  • So I can't find a real solution. I know toFixed() does work, however you need to give the total digits you want to receive back.

    Per example:

     var nr = 1e-7;     
     console.log(nr.toFixed(10)) //=> 0.0000001000
    

    that's not really nice to see as well. So this script does work. However Javascript can mess it up again. Per example I was using D3 to create a graph and although the number is going in there with normal notation, it will come out again in scientific... So it is very fragile...

    function newToFixed(nr) {
        arr1 = (""+nr).split("e"),
        arr2 = [],
        fixedPos = null;
    
        //notation is already normalized
        if (arr1.length === 1) {        
            return nr;
        }
    
        /**
         * remove the + or - from the number 
         * now have the exact number digits we want to use in toFixed
         */
        if (arr1[1].indexOf("+") === 0) {
            arr2 = arr1[1].split("+");
        } else {
            arr2 = arr1[1].split("-");
        }
    
        //making sure it is a number and not a string
        fixedPos = Number(arr2[1]); 
        return nr.toFixed(fixedPos); //returns  0.0000001
    }