Displaying score with zeros in front of var (i.e. 0025 instead of 25)

I am trying to display a score variable in my GUI with a certain amount of zeros in front of the variable number. So instead of showing my score as “25” I want to be displayed as “0025”.

This sounds like a simple thing to do, but I’m not sure how to google an answer.

Here’s my code:

#pragma strict

var LabelPoints : UILabel;

function Awake(){
Money = PlayerPrefs.GetInt("Money");
Points = PlayerPrefs.GetInt("Points");

}

function Update (){
// this tells the label to update the points score GUI label
LabelPoints.text = ""+points.Points;

}

function GetMoney  (){
// this adds +1 to the score in the points script
 points.Points+=1;

}

Just use ToString like this:

    LabelPoints.text = ""+points.Points.ToString("0000");

You can display it as a string instead and put the 0s in front. I’m going to show you in C# but it should be just about the same in javascript with minor differences you can figure out.

// Change to how many digits you want
int scoreLength = 4;

// this is the score
int score = 25

// score as a string
string scoreString = score.toString();

// get number of 0s needed
int numZeros = scoreLength - scoreString.length();

string newScore;
for(int i = 0; i < numZeros; i++){
     newScore += "0";
}

newScore += scoreSting;

// your newScore will now be "0025"

In your string, you could add the amount of zeros you want, and have if statements to change the number of zeros.

For example:

function Update (){
	if(points.Points <= 9){
		LabelPoints.text = "000" + points.Points;
	}
	if(points.Points <= 99){
		if(points.Points >= 10){
			LabelPoints.text = "00" + points.Points;
		}
	}
}

The correct way to do this in C# is:

 int intValue = 1023983;
    
// Display integer values by calling the ToString method.
Console.WriteLine("{0,22}", intValue.ToString("D8");
   
// Display the same integer values by using composite formatting.
Console.WriteLine("{0,22:D8} {0,22:X8}", intValue);
  
// The example displays the following output:
//                     01023983

Source: