How to round to 2 decimals with format? (123456 > 123K > 123.45K) (C#)
so i've got this script that will format long numbers up to Q and in the ToString i have added F2 which works, before it reaches 1000
1 = 1.00
10 = 10.00
100 - 100.00
1000 = 1K
1500 = 1K
decimals dont work when the number is formatted, also how can i remove the ".00" or ".0" for numbers that aren't rounded, if its too much of a worry ill just do ToString("F1") but still having that .0 is annoying :/
1.00 = 1
10.00 = 10
10.10 = 10.1
using UnityEngine; using System.Collections.Generic; using System.Linq;
public class Format : MonoBehaviour { void Start() {
} } public static class AbbrevationUtility { private static readonly SortedDictionary<long, string> abbrevations = new SortedDictionary<long, string> { {1000, "K" }, {1000000, "M" }, {1000000000, "B" }, {1000000000000, "T" }, {1000000000000000, "Q" } }; public static string AbbreviateNumber(float number) { for (int i = abbrevations.Count - 1; i >= 0; i--) { KeyValuePair<long, string> pair = abbrevations.ElementAt(i); if (Mathf.Abs(number) >= pair.Key) { int roundedNumber = Mathf.FloorToInt(number / pair.Key); return roundedNumber.ToString() + pair.Value; } } return number.ToString("F2"); } }
Ideally:
1 = 1
= 1.2
1.23 = 1.2
1234.56 = 1.2K
1234567890 = 1.2B
Comment