using System.Globalization; using System.Text; using TMPro; using UnityEngine; [RequireComponent(typeof(TextMeshProUGUI))] public class digits_sheet_auto : MonoBehaviour { [SerializeField, Tooltip("要显示的数字,支持小数和负数")] private double value; [SerializeField, Tooltip("是否显示千分位逗号")] private bool showComma = true; [SerializeField, Tooltip("最多保留几位小数,尾数为 0 时不显示")] private int decimalPlaces = 3; private TextMeshProUGUI label; private void Awake() { label = GetComponent(); if (label == null) label = gameObject.AddComponent(); label.richText = true; Refresh(); } private void OnValidate() { label = GetComponent(); if (label != null) Refresh(); } public void SetValue(double newValue) { value = newValue; Refresh(); } private void Refresh() { if (label == null) return; int places = Mathf.Clamp(decimalPlaces, 0, 15); string format = showComma ? "#,##0" : "0"; if (places > 0) format += "." + new string('#', places); string number = value.ToString(format, CultureInfo.InvariantCulture); label.text = ToSpriteTags(number); } private static string ToSpriteTags(string number) { var sb = new StringBuilder(number.Length * 24); foreach (char c in number) { if (c >= '0' && c <= '9') sb.Append(""); else if (c == ',') sb.Append(""); else if (c == '.') sb.Append(""); else sb.Append(c); // 图集里没有负号,负号退回普通字体 } return sb.ToString(); } }