How to Get the Length of a Number in JavaScript

Last updated on August 11, 2022
How to Get the Length of a Number in JavaScript

1. length Property of String Representation

To get the length of a number, call the toString() method on the number to convert it to a string, then access the length property of the string, i.e., num.toString().length.

const num1 = 12345;
const num2 = 524;

console.log(num1.toString().length); // 5
console.log(num2.toString().length); // 3

We call the toString() method on the number to get its string representation.

const num1 = 12345;
const num2 = 524;

console.log(num1.toString()); // '12345'
console.log(num2.toString()); // '524'

String objects have a length property that returns the number of characters (UTF-16 code units) in a string. We use this to get the length of the number.

Getting the Length of Floats

For floating point numbers, the decimal point will be included when accessing the length property of the string representation of the float.

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(float1.toString().length); // 6
console.log(float2.toString().length); // 5

To avoid this and get the actual number of digits in the float, simply subtract 1 from length.

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(float1.toString().length - 1); // 5
console.log(float2.toString().length - 1); // 4

2. Math.ceil() and Math.log10() Methods

We can also use a purely mathematical approach to get the length of a number:

function getNumberLength(num) {
  return Math.ceil(Math.log10(num + 1));
}

const num1 = 12345;
const num2 = 524;

console.log(getNumberLength(num1)); // 5
console.log(getNumberLength(num2)); // 3

The Math.log10() method returns the logarithm of a number to the base 10.

console.log(Math.log10(12345)); // 4.091491094267951

And the Math.ceil() method rounds a number up to the next largest integer.

console.log(Math.ceil(4.091491094267951)); // 5

Unfortunately, this method doesn't work for floats. It only returns the number of digits before the decimal point.

function getNumberLength(num) {
  return Math.ceil(Math.log10(num + 1));
}

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(getNumberLength(float1)); // 3
console.log(getNumberLength(float2)); // 3

See also