How to Get a Count of the Total Number of Digits in a Number

How can I get a count of the total number of digits in a number?

Without converting to a string you could try

Math.Floor(Math.Log10(n) + 1);

Get number of digits with JavaScript

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

Finding the number of digits of an integer

There's always this method:

n = 1;
if ( i >= 100000000 ) { n += 8; i /= 100000000; }
if ( i >= 10000 ) { n += 4; i /= 10000; }
if ( i >= 100 ) { n += 2; i /= 100; }
if ( i >= 10 ) { n += 1; }

How can I get a count of the total number of digits in a number in TypeScript?

in typescript simply use:

this.number.toString().split('.'))[1].length

Where this.number is Type of Number

How to find length of digits in an integer?

If you want the length of an integer as in the number of digits in the integer, you can always convert it to string like str(133) and find its length like len(str(123)).

How do I determine the number of digits of an integer in C?

floor (log10 (abs (x))) + 1

http://en.wikipedia.org/wiki/Logarithm

How can I make this function count the number of digits in a float?

If you just want to count how many values are in the number you can modify your code as follows (only for positive floats and integers)

count = len(num.replace('.', ''))

To work around with negative values you can use json module. It will cover you mantisa case.

import json
def count_digits(num):
num = json.loads(num) # returns type bound value
digit_str = str(abs(num)).replace('.', '')
return len(digit_str)

Try:

my_float = '1e+30'
actual_float = json.loads(my_float)
print(type(actual_float)) # returns <class 'float'>

Notice: json.loads works only with string objects, so you're good to go with applying this function to your arguments as they are strings by default.


You can also use re module (regular expressions):

import re
def count_digits(num):
return len(re.sub(fr'[.+-]', '', num))

Here you use re.sub to substitute ., +, and - sign for nothing and return the length of the resulting string.
Notice: with re module you're working with strings!


The last approach I can come up with is by using eval function

eval('-1e+15')

How to count digits of given number?

The problem is that the division operation will eventually end up converting x to a float and you'll have something like:

x / 10 === 0.1;
x / 10 === 0.01;
x / 10 === 0.001;
....

if you always parse (round) the result of the division to an integer, you'll get the expected result.

var num;var count = 0;
num = prompt('Enter number: ');
function counter(x, y) { while (x > 0) { y++; x = parseInt(x / 10); } return y;}
var result = counter(num, count);
console.log(result);

Count number of digits - which method is most efficient?

The following is even more efficient:

int findn(int num)
{
if ( num < 10 )
return 1;
if ( num < 100 )
return 2;
//continue until max int
}

You could optimize this even further by doing a binary search, but that would be overkill.



Related Topics



Leave a reply



Submit