本文介绍了格式化号码与指标preFIX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

无论是指标preFIX 是preferable到的可待讨论,但我认为它有它的使用情况进行物理单位。

Whether a metric prefix is preferable to the scientific notation may be up for debate but i think it has its use-cases for physical units.

我看看周围,但它似乎.NET并没有像建于什么,还是我弄错了?实现这一目标的任何方法就可以了。

I had a look around but it seems .NET does not have anything like that built in, or am i mistaken about that? Any method of achieving that would be fine.

作为澄清:我们的目标是要显示任何给定的数字作为浮点或者整串与1和999和相应的度量preFIX之间的值

As a clarification: The goal is to display any given number as a floating point or integer string with a value between 1 and 999 and the respective metric prefix.

例如。

1000 - > 1K
0.05 - >50米

1000 -> 1k
0.05 -> 50m

使用某些圆整:

1436963 - > 1.44M

1,436,963 -> 1.44M

推荐答案

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

Try this out. I haven't tested it, but it should be more or less correct.

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

这篇关于格式化号码与指标preFIX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 09:49