How to get first 2 non zero digits after decimal in javascript
javascript
Solution
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.
Problem
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 then my function should return 0.000000025. Can any one have an idea of how this can be achieved in javascript? The result should be a float number not a string.