In my game I need to get the individual value of digit in score. For example, if my score is 143 I need to get the second digit’s value, which in this case would be 4.
I’ve done an animation for my score that goes from 0 to 9. And I’ve got it working up to 9 but if my score exceeds 9 then nothing happens. So I thought I could just add another game object (that has score animation in it) next to the other number, but that would only read the second digit’s value from my score. And then also the same thing for the third number.
I hope you understood what I’m trying to achieve
Here’s what I have now. And only the first digit is working. If you have some better ways to implement this score counter please tell me.
Perhaps a better way to do it is this: 143 modulo 10 is 3, 143 modulo 100 is 43, 143 modulo 1000 is 143, etc. So if you’re looking for the second digit, you would subtract 143 modulo 10 from 143 modulo 100 to get 40, then divide by 10.
For different digits: the ones place just involves taking 143 modulo 10 minus 143 modulo 1 (which is zero) to get 3, then dividing by one. The hundreds place involves taking 143 modulo 1000 minus 143 modulo 100 to get 100, then dividing by 100. Hopefully you get the idea.
What I usually do it divide by a multiple of 10 and then truncate the decimal by converting to an int. All that’s left is to use a modulus to get the value. For instance, I would take 143 and cast it to a float, and then divide by 10 to get 14.3. The cast it back to an int to get 14. Finally modulate it by 10 and out pops a 4.
public static int digit(int val, int digit)
{
float v = (float)val /= Math.pow(10, digit - 1);
int i = (int)v;
return i % 10;
}