javascriptnumbersdecimaltofixed

JS decimal number problem need a function similar to toFixed()


var num = 20.3698  //20.37
var num = 0.36587  //0.37
var num = 0.000014247 //0.000014
var num = 0.0000000000099879 //0.000000000001

I am facing a problem in my JavaScript code: I have some random large and small decimal numbers which on printing takes too much space on view pane.

Example: var num = 0.023810002044 is okay because here I can use toFixed(2) but numbers like this 0.00000000008824721 take much space and if I use toFixed(2) then it will give me 0.00 but I want 0.00000000009 and if given a number like 0.03248 then output should be 0.03.


Solution

  • You could take the logarithm of 10 and adjust smaller numbers.

    const
        fix = v => v > 0.01
            ? v.toFixed(2)
            : v.toFixed(1 - Math.floor(Math.log10(Math.abs(v))));
        
    console.log([20.3698, 0.36587, 0.000014247, 0.00000000008824721, 0.0000000000099879].map(fix));