David Ndckr
David Ndckr

Reputation: 97

get digits count in an integer without converting to string

is it possible to count numerical digits in the integer? Eg.: 232354 is 6 digits, 456 is 3 digits.

I would normally do for example in C# something like:

var count =  myInteger.ToString().Length;

But as I want to use it in HLSL (Unity shader), using the string is out of the question (or ?). Any hint would be very much appreciated.

Upvotes: 1

Views: 2190

Answers (2)

Mars Buttfield-Addison
Mars Buttfield-Addison

Reputation: 181

One way to get the number of digits in a base-10 integer is using logarithm. Log10 will give you the base in power of 10 (e.g. number of times 10 can be multiplied by and still be below this number) so you want to add 1 to get the number of places. Log can return fractional remainder so you want to floor it to get the appropriate integer value first.

var count = Mathf.FloorToInt(Mathf.Log10(myInteger)) + 1;

Upvotes: 1

Karan
Karan

Reputation: 46

You can use the below :

int count = (int)Math.floor(Math.log10(myInteger) + 1);

PS : It won't work on negative numbers.

Another generic but elongated solution :

  int count = 0;
    while (yourInteger != 0) {
        yourInteger = yourInteger / 10;
        ++count;
    }
  return count;

Upvotes: 3

Related Questions