Skip to content Skip to sidebar Skip to footer

How To Get First 2 Non Zero Digits After Decimal In Javascript

I need to get the first 2 non zero digits from a decimal number. How can this be achieved? Suppose I have number like 0.000235 then I need 0.00023, if the number is 0.000000025666

Solution 1:

Here are two faster solutions (see jsperf) :

Solution 1 :

var n = 0.00000020666;
var r = n.toFixed(1-Math.floor(Math.log(n)/Math.log(10)));

Note that this one doesn't round to the smallest value but to the nearest : 0.0256 gives 0.026, not 0.025. If you really want to round to the smallest, use this one :

Solution 2 :

var r = n.toFixed(20).match(/^-?\d*\.?0*\d{0,2}/)[0];

It works with negative numbers too.

Solution 2:

var myNum = 0.000256var i = 1while(myNum < 10){
    myNum *= 10
    i *= 10
}
var result = parseInt(myNum) / i

Solution 3:

With numbers that has that many decimals, you'd have to return a string, as any parsing as number would return scientific notation, as in 0.000000025666 would be 2.5666e-8

functionround(n, what) {
    var i = 0;
    if (n < 1) {
        while(n < 1) {
            n = n*10;
            i++;
        }
    }
    return'0.' + (newArray(i)).join('0') + n.toFixed(what).replace('.','').slice(0,-1);
}

FIDDLE

Post a Comment for "How To Get First 2 Non Zero Digits After Decimal In Javascript"