c# - 格式化带有公制前缀的数字?

这个问题在这里已经有了答案:
关闭10年前.

Possible Duplicate:
Engineering notation in C#?

是否为 metric prefix优于 scientific notation可能有争议,但我认为它有其物理单位的用例。

我环顾四周,但似乎 .NET 没有内置类似的东西,还是我弄错了?任何实现这一点的方法都可以。

澄清一下:目标是将任何给定数字显示为 float 或整数字符串,其值介于 1 和 999 之间,并带有相应的度量前缀。

例如

1000 -> 1k
0.05 -> 50m

四舍五入:

1,436,963 -> 144 万

最佳答案

试试这个。我没有测试过,但它应该或多或少是正确的。

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;
}

https://stackoverflow.com/questions/12181024/

相关文章:

html - 如何处理 XSLT 中嵌入的 XML 标记?

ruby - Emacs ruby​​ 模式缩进行为

java - 格式化传递给Java函数的多个参数

r - 如何为 rmarkdown PDF 输出格式化复杂表格

visual-studio - 使用标准格式将 Visual Studio 复制/粘贴到 Outlo

vba - 是否有将 Excel 文件格式/设置保存到对象的标准过程?

r - 在r中将多列从字符转换为数字格式

intellij-idea - Intellij 中的链式方法和连续缩进

c# - 将零值格式化为空字符串?

javascript - 逗号优先的 JS 格式化程序