Reputation: 97
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
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
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