Skip to content

JavaScript length of number | HTML example code

  • by

First, convert the number to string using the toString() inbuilt method. Then use the length() method to get the length of the number in JavaScript.

var x = 123456789;

x.toString().length;

JavaScript length of number Example

Complete HTML example code:

Note: This process will also work for Float Numbers and for Exponential numbers also.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script>
		var x = 123456789;

		var res =  x.toString().length;
		alert(res);

	</script> 
</body> 
</html>	

Output:

JavaScript length of number example code

If you don’t want to use the toString() method then add an empty string. It will implicitly cause a number to turn into a string.

var mynumber = 123;
alert((""+mynumber).length);

One more Math (best performance in Chrome, Firefox but slowest in ie11)

var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)

Do comment if you have any doubts and suggestions on this JS number topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading