Get the position of first not 0 decimal digit

Viewed 486

I need to find the position of the first not "0" decimal digit. For instance

a = 0.00056;

the fist not "0" digit after the dot is 5, and the searched position is 4. Is there a javascript function already built or an elegant way to get it in javascript?

Just for curiosity, I then will keep 0.00001 as stepping value in a slider the maximum value of which is the variable a.

3 Answers

You could take the logarithm of ten and take a floored value.

var a = 0.00056,
    p = Math.floor(Math.log10(a));

console.log(p);

You can do this with string manipulation, or with pure numbers.

The mathematical way is:

Math.floor(Math.abs(Math.log10(n))); // if n >= 0 && n < 1

let arr = [
  0.56,    // 0
  0.056,   // 1
  0.0056,  // 2
  0.00056, // 3
  0.000056 // 4
];

arr.forEach(a => {
  console.log(`n = ${a}, str = ${getFirstNonZeroStr(a)}, log = ${getFirstNonZeroLog(a)}`);
});

function getFirstNonZeroStr(n) {
  if (n >= 1) return -1;
  let s = n.toString();
  let m = s.match(/^0\.(0*)[\d]+$/);
  return m[1].length;
}

function getFirstNonZeroLog(n) {
  if (n >= 1) return -1;
  return Math.floor(Math.abs(Math.log10(n)));
}

Just adding another way by converting it to a string and using a reg exp

a = 0.00056;
console.log(a.toString().match(/0\.(0*[^0])/)[1].length)

Related