-1

I'm trying to get the number of digits of a number in javascript, but I'm running into some edge cases with the equations I've found online.

Here's what I'm using, from this site.

getNumDigits(val){
  return val === 0 ? 1 : Math.floor(Math.log(Math.abs(val)) / Math.LN10 + 1);
}

But the problem with this is, if you put in a number like 1000, you somehow get a javascript rounding error where the value comes out like 3.999997

I've noticed that, as long as your number isn't between -1 and 1, you can just add 1 to the val in the Math.abs(val) and it will appropriately set the number of digits, but it just seems messy.

I've tried just converting the val into a string, and getting the length, but that doesn't work in the case of, say, a decimal, where you're using something like 0.2 - as it will say the length is 3.

What's a good equation / function to use?

mheavers
  • 29,530
  • 58
  • 194
  • 315

1 Answers1

1

Making the number a string and using a regex to only count the digits can work.

function getNumDigits(val) {
  return (`${val}`.match(/\d/g) || []).length
}

console.log(getNumDigits(2.5245234))
Callam
  • 11,409
  • 2
  • 34
  • 32