格式C#Double to Scientific Notation in powers of multipleles of three

时间:2011-08-10 13:05:29

标签: c# double string-formatting scientific-notation

我正在尝试以科学格式格式化一些大数字,但我需要三倍的倍数。有推荐的方法吗?

我在表格中有一系列数字,而不是真正的科学格式(小数点前面有一个数字)我很高兴有这样的改变,以获得三倍的幂,例如:

3.123e + 003
19.523e + 003

而不是:

3.123e + 003
1.952e + 004

拥有所有权力为三的倍数使我的桌子更容易扫描,我相信。

提前致谢

1 个答案:

答案 0 :(得分:4)

我认为你需要编写自己的函数。 首先,您可以获得数字的科学表示,其精度比您需要的大两位数。 然后你应该解析结果字符串以获得浮点系数和10的幂指数作为十进制类型的数字。之后,您将除法指数的余数除以3并以适当的方式更改数字。最后生成输出字符串。

static string Scientific3(double value, int precision)
{
    string fstr1 = "{0:E" + (precision+2).ToString() + "}";
    string step1 = string.Format(fstr1, value);
    int index1 = step1.ToLower().IndexOf('e');
    if (index1 < 0 || index1 == step1.Length - 1)
        throw new Exception();
    decimal coeff = Convert.ToDecimal(step1.Substring(0, index1));
    int index = Convert.ToInt32(step1.Substring(index1 + 1));
    while(index%3!=0)
    {
        index--;
        coeff *= 10;
    }
    string fstr2 = "{0:F" + precision.ToString() + "}E{1}{2:D3}";
    return string.Format(fstr2, coeff, ((index < 0) ? "-" : "+"), Math.Abs(index));
}