-1

I'm looking to format my int into strings that shorten the number. i.e.

1 -> 1
10 -> 10
100 -> 100
1000 -> 1K
1100 -> 1,1K
10000 -> 10K
11000 -> 10K
100000 -> 100K
1000000 -> 1M

etc...

I tried some code snippets I found already on stack overflow such as

public class Test
{
    public string MyMethod(int num)
    {
        if (num >= 1_000)
        {
            return (num / 1_000).ToString("0.#") + "K";
        }
    }
}

this worked to an extent, however, I'm not sure what the formatting "0.#" does and I can't find anything online to explain it. There are some further examples on the same post which cover some other formatting types such as "#,0K" but again, I don't know the difference so I can't customise these to how I like them.

Tyler Jay
  • 27
  • 5

1 Answers1

0

simple if/else approach (https://dotnetfiddle.net/yrea4D)

public static string GetFormat(int value)
{
    if (value >= 1000000)
    {
        return (value / 1000000m) + "M";
    }
    else if (value >= 1000)
    {
        return (value / 1000m) + "K";
    }
    else
    {
        return value.ToString();
    }
}
fubo
  • 44,811
  • 17
  • 103
  • 137