问题
As the title of my post suggests, I would like to know how many digits var number
has. For example: If number = 15;
my function should return 2
. Currently, it looks like this:
function getlength(number) {
return number.toString().length();
}
But Safari says it is not working due to a TypeError
:
'2' is not a function (evaluating 'number.toString().length()')
As you can see, '2'
is actually the right solution. But why is it not a function
?
回答1:
length
is a property, not a method. You can't call it, hence you don't need parenthesis ()
:
function getlength(number) {
return number.toString().length;
}
UPDATE: As discussed in the comments, the above example won't work for float numbers. To make it working we can either get rid of a period with String(number).replace('.', '').length
, or count the digits with regular expression: String(number).match(/\d/g).length
.
In terms of speed potentially the fastest way to get number of digits in the given number is to do it mathematically. For positive integers there is a wonderful algorithm with log10
:
var length = Math.log(number) * Math.LOG10E + 1 | 0; // for positive integers
For all types of integers (including negatives) there is a brilliant optimised solution from @Mwr247, but be careful with using Math.log10
, as it is not supported by many legacy browsers. So replacing Math.log10(x)
with Math.log(x) * Math.LOG10E
will solve the compatibility problem.
Creating fast mathematical solutions for decimal numbers won't be easy due to well known behaviour of floating point math, so cast-to-string approach will be more easy and fool proof. As mentioned by @streetlogics fast casting can be done with simple number to string concatenation, leading the replace solution to be transformed to:
var length = (number + '').replace('.', '').length; // for floats
回答2:
Here's a mathematical answer (also works for negative numbers):
function numDigits(x) {
return Math.max(Math.floor(Math.log10(Math.abs(x))), 0) + 1;
}
And an optimized version of the above (more efficient bitwise operations):
function numDigits(x) {
return (Math.log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1;
}
Essentially, we start by getting the absolute value of the input to allow negatives values to work correctly. Then we run the through the log10 operation to give us what power of 10 the input is (if you were working in another base, you would use the logarithm for that base), which is the number of digits. Then we floor the output to only grab the integer part of that. Finally, we use the max function to fix decimal values (any fractional value between 0 and 1 just returns 1, instead of a negative number), and add 1 to the final output to get the count.
The above assumes (based on your example input) that you wish to count the number of digits in integers (so 12345 = 5, and thus 12345.678 = 5 as well). If you would like to count the total number of digits in the value (so 12345.678 = 8), then add this before the 'return' in either function above:
x = Number(String(x).replace(/[^0-9]/g, ''));
回答3:
Since this came up on a Google search for "javascript get number of digits", I wanted to throw it out there that there is a shorter alternative to this that relies on internal casting to be done for you:
var int_number = 254;
var int_length = (''+int_number).length;
var dec_number = 2.12;
var dec_length = (''+dec_number).length;
console.log(int_length, dec_length);
Yields
3 4
回答4:
If you need digits (after separator), you can simply split number and count length second part (after point).
function countDigits(number) {
var sp = (number + '').split('.');
if (sp[1] !== undefined) {
return sp[1].length;
} else {
return 0;
}
}
回答5:
var i = 1;
while( ( n /= 10 ) >= 1 ){ i++ }
23432 i = 1
2343.2 i = 2
234.32 i = 3
23.432 i = 4
2.3432 i = 5
0.23432
回答6:
Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor()
. Direct to the point check this out!
function digitCount ( num )
{
return Math.floor( num.toString()).length;
}
digitCount(2343) ;
// ES5+
const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;
console.log(digitCount2(3343))
Basically What's going on here. toString()
and String()
same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length
.
Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs()
in it;
Cheer You!
回答7:
I'm still kind of learning Javascript but I came up with this function in C awhile ago, which uses math and a while loop rather than a string so I re-wrote it for Javascript. Maybe this could be done recursively somehow but I still haven't really grasped the concept :( This is the best I could come up with. I'm not sure how large of numbers it works with, it worked when I put in a hundred digits.
function count_digits(n) {
numDigits = 0;
integers = Math.abs(n);
while (integers > 0) {
integers = (integers - integers % 10) / 10;
numDigits++;
}
return numDigits;
}
edit: only works with integer values
回答8:
Two digits: simple function in case you need two or more digits of a number with ECMAScript 6 (ES6):
const zeroDigit = num => num.toString().length === 1 ? `0${num}` : num;
回答9:
Problem statement: Count number/string not using string.length() jsfunction. Solution: we could do this through the Forloop. e.g
for (x=0; y>=1 ; y=y/=10){
x++;
}
if (x <= 10) {
this.y = this.number;
}
else{
this.number = this.y;
}
}
回答10:
it would be simple to get the length as
`${NUM}`.length
where NUM is the number to get the length for
回答11:
Here is my solution. It works with positive and negative numbers. Hope this helps
function findDigitAmount(num) {
var positiveNumber = Math.sign(num) * num;
var lengthNumber = positiveNumber.toString();
return lengthNumber.length;
}
(findDigitAmount(-96456431); // 8
(findDigitAmount(1524): // 4
回答12:
The length property returns the length of a string (number of characters).
The length of an empty string is 0.
var str = "Hello World!";
var n = str.length;
The result of n will be: 12
var str = "";
var n = str.length;
The result of n will be: 0
Array length Property:
The length property sets or returns the number of elements in an array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
The result will be: 4
Syntax:
Return the length of an array:
array.length
Set the length of an array:
array.length=number
来源:https://stackoverflow.com/questions/14879691/get-number-of-digits-with-javascript