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

Formatting a number with a metric prefix?(格式化带有公制前缀的数字?)

本文介绍了格式化带有公制前缀的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

公制前缀是否优于科学记数法可能有争议,但我认为它有物理单位的用例.

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 之间,并带有相应的度量前缀.

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 -> 50m

1000 -> 1k
0.05 -> 50m

四舍五入:

1,436,963 -> 144 万

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

这篇关于格式化带有公制前缀的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:格式化带有公制前缀的数字?

基础教程推荐