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

Asked
Active3 hr before
Viewed126 times

4 Answers

javascriptfirst
90%

Here are two faster solutions (see jsperf) :,To learn more, see our tips on writing great answers., My solutions are simpler and much more fast : jsperf.com/round-to-2-significant-digits ;) – Denys Séguret May 27 '14 at 11:45 , +1 This is the solution you are after praveen, see Fiddle – urbz May 27 '14 at 11:07

Solution 1 :

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

Solution 2 :

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

var myNumber = 12.2345;
var myNumberWithTwoDecimalPlaces = parseFloat(myNumber).toFixed(2); //12.23
load more v
72%

I need to get the first 2 non zero digits from a decimal number. How can this be achieved?,Can any one have an idea of how this can be achieved in javascript?,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.,It works with negative numbers too.

Solution 1 :

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

Solution 2 :

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

That’s because a sign is represented by a single bit, so it can be set or not set for any number including a zero.,The method toFixed(n) rounds the number to n digits after the point and returns a string representation of the result.,Returns a random number from 0 to 1 (not including 1).,Please note that result of toFixed is a string. If the decimal part is shorter than required, zeroes are appended to the end:

let billion = 1000000000;
load more v

Other "javascript-first" queries related to "How to get first 2 non zero digits after decimal in javascript"