- Home /
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;
}
Answer by Slobdell · Aug 17, 2013 at 08:38 PM
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"
Thanks! XD I know this is back from 2013, but I got it working!
Answer by RomanorumLegio · Aug 17, 2013 at 08:28 PM
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;
}
}
}
Answer by tenryu · Jul 09, 2017 at 07:28 PM
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: https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
Your answer
Follow this Question
Related Questions
Showing score with GUI 2 Answers
Scoring with positions 1 Answer
3D ^ Custom GUIText/Label or Making a Score System without using GUI? 0 Answers
Count the Score 1 Answer
Trying to add 1 point to score, but it is adding 2. 2 Answers