How to get the Length of a Number in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Jan Padilla

Get the Length of a Number in JavaScript #

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.

index.js
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.

index.js
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.

index.js
const float = 123.45; const withDot = float.toString().length; console.log(withDot); // ๐Ÿ‘‰๏ธ 6 const withoutDot = float.toString().length - 1; console.log(withoutDot); // ๐Ÿ‘‰๏ธ 5
If you need to get the length of a float, without counting the dot, subtract 1from 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.

index.js
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.

index.js
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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee