Value to string?

I know this is some really first-level stuff here, but I don’t know if I have ever before had an actual use for this, so I don’t recall how to do it.

How to find the value of a particular digit in a regular variable?

For example, an int with a value of 12,345 has a “4” for the second digit from the decimal point. (Or the fourth digit, depending upon how you count it.)

If I recall correctly, I can cast or convert the int value into a string, and then read the character at x places into the string. But I don’t recall how to do this. It always sounded like such a stupid operation to me, so I never paid much attention.

I’m doing this to create a “score” counter to display on my HUD, but I’m not displaying it with a standard piece of text, but rather using a set of images. So unless someone knows of a smarter way, I figure I need to read each digit individually and display the correct texture for each digit.
Also, I kind of need to draw some zeroes at the front of this number, so I’d need to convert my uint into a 10-character string. I could do that by counting the length of the string and concatenate some 0’s at the front of it, but I also wonder if there is a built-in feature to convert a variable into a string of a specified length.

score.ToString(“0000000000”)[9], for the tenth char entry in the string (which is like an array of chars). Perhaps a smarter way would be to use a custom bitmap font, so you could just display the score normally without having to program any of that.

–Eric

The mathematical approach would be something like.

int x = 12345;
int digit;
while(x>0){
       digit = x%10;
       Debug.Log(digit);
       x /=10;
}

will output

5
4
3
2
1

You can use those to pass to whatever is creating these ‘images’ to determine the right image to display.

For a method involving casting types, something like

int x = 12345;

foreach (char c in x.ToString()){
    var digit = Char.GetNumericValue(c);  
    Debug.Log(digit);
}

This will output in the other order:

1
2
3
4
5

x.ToString().Length will tell you how many leading zeros you need, as well.

1 Like

Where can I find some reading on that subject?

In the olde days this would work, but things were changed somewhat in Unity 4 and made more complicated. Probably the simplest is to use an asset to handle it, like this one which is the first that came up in a search, but there are others too I think.

–Eric

1 Like