How to Convert Numbers to Letters in Unity – Unity By Example

How to Convert Numbers to Letters in Unity

Converting numbers to text can be useful in various situations, especially in game development. In Unity, for example, converting numbers to a word representation can be used for displaying the quantity of game resources, scores, levels, time, etc. It can also be helpful for creating customizable interfaces where numbers need to be displayed in words. In this article, we will explore how to convert numbers to words in Unity and provide examples of using this functionality in various game development scenarios.

Steps

  • Create script NumberShortener.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Numerics;
using TMPro;

public class NumberShortener : MonoBehaviour
{
    [SerializeField] private double _number = 2023;
    [SerializeField] private TMP_Text _money;

    private List<char> _suffixes = new List<char>() { 'K', 'M', 'B' /* etc */ };

    private void Start()
    {
        RefreshMoney();
    }

    private string FormatNumber()
    {
        double number = _number;
        char? suffix = null;

        for (int i = 0; i < _suffixes.Count; i++)
        {
            if (number >= 1000)
            {
                suffix = _suffixes[i];
                number /= 1000;
            }
            else
            {
                break;
            }
        }

        return string.Format($"{number.ToString("#.##")}{suffix}");
    }

    private void RefreshMoney()
    {
        _money.text = FormatNumber();
    }
}
  • Create empty object and Add script NumberShortener.cs
  • Fill in the fields with data in the inspector. Enter the output number and TMPText object.

Download

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments