How To Get The Length Of A Number In JavaScript

How to get the Length of a Number in JavaScript

To get the length of a number in JavaScript, you can convert the number to a string to get its length. The specific steps are below. Let’s get started.

How to get the length of a number in JavaScript

Convert the number to a string and take the string length

We can call the toString() technique on the number to switch it over entirely to a string. Then, at that point, access the length property of the string. Following the code below to understand.

Syntax:

number.toString().length

Parameters: None

Return: length of number

Get the length of an integer number

Code example:

const number1 = 953167; // 6
const number2 = 4562; // 4
console.log("The length of number", number1, "=", number1.toString().length);
console.log("The length of number", number2, "=", number2.toString().length);

Output:

The length of number 953167 = 6
The length of number 4562 = 4

Get the length of a float number

The decimal point will be incorporated while getting to the length property of the string portrayal of the float.

Code example:

const floatNumber1 = 12312.4512;
console.log("The length of float number", floatNumber1, "=", floatNumber1.toString().length - 1) // 9
const floatNumber2 = 524521.1;
console.log("The length of float number", floatNumber2, "=", floatNumber2.toString().length - 1);; // 7

Output:

The length of number 12312.4512 = 9
The length of number 524521.1 = 7

Use Math.ceil() and Math.log10() methods

You can use a simple numerical way to deal with getting the length of a number.

Code example:

function getLength(number) {
	return Math.ceil(Math.log10(number + 1));
}

const number1 = 9531642;
console.log("The length of number", number1, "=", getLength(number1)); // 7
const number2 = 1231;
console.log("The length of number", number2, "=", getLength(number2)); // 4

Output:

The length of number 9531642 = 7
The length of number 1231 = 4

In the code line above, the Math.log10() function returns a number of logarithm base 10, and the Math.ceil() function returns a number that is rounded. 

Code example:

number = 62512;
console.log("The logarithm of base 10",number, "is",Math.log10(number)); // 4.795963393880709
console.log("The round logarithm of base 10",number, "is",Math.ceil(Math.log10(number))); // 5

Output:

The logarithm of base 10 62512 is 4.7959633938807095
The round logarithm of base 10 of 62512 is 5

Summary

This article shows you how to get the length of a number in JavaScript. The two methods mentioned in this article are the most straightforward approaches. Hopefully, they will help you. Leave a comment below if you have any problems.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *