Format Numbers
Part of the Building Real Games section of Coddy's Unity journey. Lesson 3 of 56.
A number joined to a string comes out the way C# writes it: a timer shows 12.34567, and a float that is 2 shows 2, with no decimals at all. A format string in ToString() decides how it looks instead. Each 0 in it stands for a digit that is always written: 7.ToString("000") is 007, and 41.27f.ToString("0.0") is 41.3, rounded to one decimal. In string interpolation the same format goes after a colon: $"{coins:000}", $"{topSpeed:0.0} m/s".
Times read better as minutes and seconds. Cast the time to int first, which drops the fraction; then integer division by 60 gives the whole minutes and % 60 the seconds left over. A lap of 83.46 seconds:
float lapTime = 83.46f;
int total = (int)lapTime; // 83
int minutes = total / 60; // 1
int seconds = total % 60; // 23
lapText.text = $"Lap: {minutes}:{seconds:00}"; // Lap: 1:23The 00 keeps two digits: without it, a lap of 64 seconds would read 1:4 instead of 1:04. And because (int) drops the fraction instead of rounding, 59.7 seconds shows as 0:59; rounding would show 0:60 for a moment.
Challenge
EasyThe arcade's Scoreboard.cs shows its numbers raw. Space scores 100 points times the combo and raises the combo by 0.5, and playTime counts the seconds played (the Inspector starts it at 47.5). Keep the counting as it is, and change how the three texts are written:
scoreText: the score in six digits, asScore: 000450.comboText: the combo with one decimal, asCombo: x2.5, andCombo: x1.0at the start.timeText: minutes and whole seconds, asTime: 2:07. The seconds always have two digits and are never rounded up.
Press Play, score a few times, then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class Scoreboard : MonoBehaviour
{
public TMP_Text scoreText;
public TMP_Text comboText;
public TMP_Text timeText;
public int score;
public float combo = 1f;
public float playTime;
void Update()
{
playTime += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Space))
{
score += (int)(100 * combo);
combo += 0.5f;
}
scoreText.text = "Score: " + score;
comboText.text = "Combo: x" + combo;
timeText.text = "Time: " + playTime;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap