3

A normal scoreboard text is like this

enter image description here

so i want to make te text format like this

enter image description here

this is the code

    score = (TextView)findViewById(R.id.ct);
    score.setText(String.valueOf(gamescore));

                    if (gamescore > highscore){
                        high.setText(String.valueOf(gamescore));
                     }

Anyone can explain? Thank's

Ricci
  • 217
  • 5
  • 21

1 Answers1

1

You should use the String.format() method along with the formatter syntax. String.format() can be used to left-pad a string with zeroes, just like you want.

This code will give you the results that you want: high.setText(String.format("%06d", gamescore));

Let's look at what's going on in detail. We are using this syntax: %[flags][width]conversion

  • Always begin the format string syntax with a %.
  • Following % is 0, the zero-padding flag. This tells the formatter that the result will be zero-padded.
  • After the zero-padding flag is the width, or the minimum number of digits we want; in this case, 6.
  • Lastly, specify the conversion type. The desired result is formatted as a decimal integer, so we use d.

Here is an example:

int gamescore = 100;
String result = String.format("%06d", gamescore);
System.out.println(result);

Output: 000100

Mitch Talmadge
  • 4,638
  • 3
  • 26
  • 44