architecture
[Scripting] Robust Large Number Suffixing with Iterative Loops
Solution
Unity 2021.3.x - Unity 6.3.x
Published 29 days ago
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.
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.
[Physics2D] 2D Raycast Component Filtering Issues[Burst] Resolve BC1091 Static Constructor Compilation Errors[Physics2D] Prevent Collision Tunneling using Low-Level Physics 2D Thresholds
Content inspired by a Unity discussion post.