Suppose we have the variable num
with some number:
let num = 12345;
Let's find the number of digits in this number.
As you already know, to find the length of a
string, you can use the property length
.
However, it only works on strings, and when applied to a number, it won't work:
let num = 12345;
alert(num.length); // shows undefined
To solve the problem, we convert our number to a string and find the length of this string:
let num = 12345;
let str = String(num); // convert our number to a string
alert(str.length); // find the length of the string
You can not involve the intermediate
variable str
, but apply the property
length
immediately to the result
of the function String
:
let num = 12345;
alert(String(num).length); // find the length of the string
Given a variable with a number. Find the number of digits in this number.
Given two variables with numbers. Find the number of digits in one and the second number, add the results and display it on the screen.