Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Jan Padilla
To get the length of a number, call the toString()
method on the number to
convert it to a string and access the length
property on the string. The
length
property returns the number of code units in the string.
const integer = 123456; const float = 123.45; console.log(integer.toString().length); // 👉️ 6 console.log(float.toString().length); // 👉️ 6
In both of the examples, we used the Number.toString method to convert the number to a string.
const integer = 123456; const str = integer.toString(); console.log(str); // 👉️ '123456'
After we convert the number to a string, we can safely access the string's
length
property.
Note that when trying to get the length of a float number the length
property
also counts the dot .
character.
const float = 123.45; const withDot = float.toString().length; console.log(withDot); // 👉️ 6 const withoutDot = float.toString().length - 1; console.log(withoutDot); // 👉️ 5
1
from the return value of the length
property.In case you don't like using the Number.toString
method, you can use a
template literal.
To get the length of a number, wrap the number in a template literal to
convert it to a string and access the length
property on the string, e.g.
${100}
.length.
const integer = 123456; const intLen = `${integer}`.length; console.log(intLen); // 👉️ 6 const float = 123.45; const floatLength = `${float}`.length; console.log(floatLength); // 👉️ 6
In this example we achieve the same result, by using a template literal to convert the number into a string.
The ${}
part of the template literal allows us to embed an expression, which
gets evaluated.
A perhaps more direct and straight forward approach is to simply pass the number
to the String
object.
To get the length of a number, pass the number as a parameter to the String
object to convert it to a string and access the length
property on the string,
e.g. String(1500).length
.
const integer = 123456; const intLen = String(integer).length; console.log(intLen); // 👉️ 6 const float = 123.45; const floatLength = String(float).length; console.log(floatLength); // 👉️ 6
The
String
object converts the type of the passed in parameter to a string, on which we can
access the length
property.