使用指标前缀格式化数字?

H.B*_*.B. 13 .net c# string formatting numbers

可能重复:
C#中的工程符号?

无论是国际单位制词头是最好的科学记数法可能为辩论,但我认为它有它的使用情况进行物理单位.

我环顾四周,但似乎.NET没有内置的东西,或者我错了吗?任何实现这一目标的方法都可以.

作为澄清:目标是将任何给定数字显示为浮点或整数字符串,其值介于1和999之间以及相应的度量标准前缀.

例如

1000 - > 1k
0.05 - > 50m

进行一些舍入:

1,436,963 - > 1.44M

Tho*_*ith 11

试试吧.我没有测试过它,但它应该或多或少是正确的.

public string ToSI(double d, string format = null)
{
    char[] incPrefixes = new[] { 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' };
    char[] decPrefixes = new[] { 'm', '\u03bc', 'n', 'p', 'f', 'a', 'z', 'y' };

    int degree = (int)Math.Floor(Math.Log10(Math.Abs(d)) / 3);
    double scaled = d * Math.Pow(1000, -degree);

    char? prefix = null;
    switch (Math.Sign(degree))
    {
        case 1:  prefix = incPrefixes[degree - 1]; break;
        case -1: prefix = decPrefixes[-degree - 1]; break;
    }

    return scaled.ToString(format) + prefix;
}
Run Code Online (Sandbox Code Playgroud)

  • 可能会对非常小或大的数字使用一些错误处理,但整体上它可以工作. (2认同)
  • 检查函数的入口是否有用,如果`d` 为0,否则`degree` 将采用`-Infinity` 值。 (2认同)