c# - 如何格式化数字以具有相同的位数?

标签 c# formatting string-formatting

我有一个标签来显示一个无符号整数,它有一个最大长度。我想格式化要显示的数字:

1           = "1"
1000        = "1,000"
12400       = "12.4k"
101,800,000 = "102M" // !!!
1,849,000   = "1.85M"

所以,我最终得到了一个最大长度为 5 的字符串。

我的范围是从 0 到 199,999,999。

有没有一种方法可以在不处理很多情况(即很多间隔)的情况下做到这一点?

最佳答案

我可能来不及了,但这里有一个扩展方法,它返回您想要的格式的数字:

public static string ToShortString(this int n)
{
    if (n >= 1e8)
    {
        return (Math.Round((double)n / 1e6, 0)).ToString() + "M";
    }
    else if (n >= 1e7)
    {
        return (Math.Round((double)n / 1e6, 1)).ToString() + "M";
    }
    else if (n >= 1e6)
    {
        return (Math.Round((double)n / 1e6, 2)).ToString() + "M";
    }
    else if (n >= 1e5)
    {
        return (Math.Round((double)n / 1e3, 0)).ToString() + "K";
    }
    else if (n >= 1e4)
    {
        return (Math.Round((double)n / 1e3, 1)).ToString() + "K";
    }
    else if (n >= 1e3)
    {
        return n.ToString("##,#");
    }
    else
    {
        return n.ToString();
    }
}

测试:

Console.WriteLine((5).ToShortString());         // displays 5
Console.WriteLine((55).ToShortString());        // displays 55
Console.WriteLine((555).ToShortString());       // displays 555
Console.WriteLine((5555).ToShortString());      // displays 5,555
Console.WriteLine((55555).ToShortString());     // displays 55.6K
Console.WriteLine((555555).ToShortString());    // displays 556K
Console.WriteLine((5555555).ToShortString());   // displays 5.56M
Console.WriteLine((55555555).ToShortString());  // displays 55.6M
Console.WriteLine((555555555).ToShortString()); // displays 556M

关于c# - 如何格式化数字以具有相同的位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11971110/

相关文章:

c# - 将 json 转换为 C# 数组?

java - 在 Windows 上格式化 Fat32 USB 驱动器

javascript - 合并堆叠的 DOM 格式化元素 - contenteditable DIV

二进制数的Python打印格式

c# - 如何在 DataGridView 中格式化带有最大值和最小值的小数列?

c# - 编译器错误 : Invalid rank specifier: expected' ,' or ' ]' on Two Dimensional Array Initialization

python - 如何循环遍历每个Excel工作表名称

python - 为什么 Python 在格式化时将此字符串解释为字典?

vb.net - 如何使用 system.drawing.stringformat 获得垂直 nowrap 字符串

c# - 表达式访问者仅为某些 lambda 表达式调用 VisitParameter