Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first 2 non zero digits after decimal in javascript

Tags:

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 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.

like image 857
praveen Avatar asked Dec 03 '22 19:12

praveen


1 Answers

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.

like image 122
Denys Séguret Avatar answered Dec 22 '22 20:12

Denys Séguret