What about checking first if number
is actually numeric and then, if it is, returning the length of its string representation:
let numbers = [undefined, null, 12345, 1.2345, '12345', '1.2345', 'abcd', '1.2345abcd', 0.1 + 0.2, 0.3, {}, []]
console.log(numbers.map(number => {
return number === null || isNaN(number) ? 0 : number.toString().length;
}));
The above snippet considers strings
that actually represent a number: 12345
, 1.2345
... as numbers.
It will return 0
for undefined
, objects, arrays and null
, but note we need to explicitly check for null
as it may not be intuitive, but isNaN(null)
will return false
. See this other answer for a detailed explanation on that.
If you don't want to count the .
, you have multiple options:
- Replace
'.'
with ''
from the string
representation of the number using String.prototype.replace()
.
- Once you know the number is actually a number, check if it is a float doing
number % 1 !== 0
and, if it is, then subtract 1
from its .length
.
You mention that you think mathjs
might be the best option to avoid harming performance, but a custom implementation to do exactly what you need is probably faster than a full blown-up library to handle "math" in general.
Also, you should probably take a look at this: https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil.
Anyway, there are a few other special cases you should consider in your custom implementation if you go for that that the library might already be handling properly, obviously with some extra work. Have you noticed what the length of 0.1 + 0.2
was according to my code? 19! How come? It looks quite obvious that 0.1 + 0.2 is 0.3, so its length should be 3. Actually, the next item on the list is 0.3
and it works fine for that one.
Well, it turns out floating-point numbers have some precision issues. I'm not going to get into that now, but you can read about it here: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems.
And here you can see an example:
console.log(0.1, 0.2, 0.3, 0.1 + 0.2)