Menu
CoddyTech

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:23

The 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 icon

Challenge

Easy

The 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, as Score: 000450.
  • comboText: the combo with one decimal, as Combo: x2.5, and Combo: x1.0 at the start.
  • timeText: minutes and whole seconds, as Time: 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;
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games