UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

architecture

[Scripting] Robust Large Number Suffixing with Iterative Loops

Solution

algorithmcomputation

Unity 2021.3.x - Unity 6.3.x

Published 29 days ago

Issue

 Sequential else if magnitude-based logic frequently fails for larger numbers because values satisfy lower-tier conditions first. For example, a number like 1,100,000 satisfies the >= 1000 condition, resulting in an output of 1100K instead of 1.1M.

Quick-Fix

Replace chained logic with a while loop and a string array. Increment a suffixIndex while dividing the value by 1000 to dynamically determine the correct magnitude.

Expand Analysis

A more robust and scalable approach to formatting large numbers involves utilizing a suffix array in conjunction with a while loop. This method streamlines the process by iteratively dividing your script value by 1000 and incrementing a suffixIndex until the value is less than 1000 or all defined suffixes have been applied. This pattern ensures that the correct magnitude and corresponding suffix are applied regardless of the initial value.

  1. Initialize a double variable with your script value.
  2. Define a string array containing the desired suffixes (e.g., "", “K”, “M”, “B”, “T”).
  3. Implement a while loop that divides the value by 1000 as long as the value is greater than or equal to 1000 and suffixes are available.
  4. Increment the suffixIndex in each loop iteration.
  5. Round the result using Math.Round and concatenate the selected suffix from the array.

Additional Tips

  • Use double instead of float for your script to prevent precision loss when dealing with quadrillions or higher magnitudes.
  • Cache the suffix array as a static or member variable to avoid unnecessary heap allocations during UI updates.
  • For high-performance scenarios, consider using StringBuilder to concatenate the final number and its suffix.

Copy


using UnityEngine;
using System;

public class NumberFormatter : MonoBehaviour
{
    public string GetFormattedValue(double value)
    {
        string[] suffixes = { "", "K", "M", "B", "T", "Q" };
        int **suffixIndex** = 0;

        while (value >= 1000 && suffixIndex < suffixes.Length - 1)
        {
            value /= 1000;
            suffixIndex++;
        }

        // Format to 2 decimal places and append the suffix
        return $"{Math.Round(value, 2)}{suffixes[suffixIndex]}";
    }
}

Related Posts Haven't quite found a solution to your problem? We think these posts might help you.

Content inspired by a Unity discussion post.