如何为我的计算器获得理想的ToString格式?

问题描述 投票:1回答:1

我是一名实习生,我制造了一个计算器。我需要以最适合自己的数字格式的帮助。我使用C#和WindowsForms。现在使用格式N:

    100 = 100,00
    1000 = 1.000,00
    more than 999 Trillion = 1.000.000.000.000.000,00 (no 10e+ x)
    0,123456789 = 0,16 (completes after two places)

我试图建立自定义格式,但我不明白。我想要的格式是:

    100 = 100
    1000 = 1.000
    1000000 = 1.000.000
    1000000000 = 1.000.000.000 
    etc.
    more than 999 Trillion = X10e+ X
    0,3 = 0,3
    0,123456789 = 0,123456789
    and at to much negative range = -x.00000000000e -x

长话短说。我需要999.999.999.999.999之后的10e +/-变体正区域中每3步需要一个点(1.000、100.000、1.000.000)否,00为正常整数和0,00000000000足够的地方我在Google中搜索了很多内容,有人可以帮忙吗?

c# winforms format calculator tostring
1个回答
0
投票

不确定这是您最终想要的格式,但是通过实施扩展,您可以设置自己的规则来获得所需的结果。我使用的是Spaniard CultureInfo,因为它使用逗号作为小数点分隔符。

public static class Extensions
{
    public static string Formatted(this double d)
    {
        if (d >= 1e+15)
        {
            return d.ToString(CultureInfo.GetCultureInfo("es-ES"));
        }
        else
        {
            return d.ToString("#,##0.###############", CultureInfo.GetCultureInfo("es-ES"));
        }
    }
}

示例:

var testValues = new List<double>()
{
    100,
    1000,
    1000000,
    1000000000,
    1000000000000000,
    0.3,
    0.123456789,
};

foreach (var value in testValues)
{
     Console.WriteLine(value.Formatted());
}

100

1.000

1.000.000

1.000.000.000

1E + 15

0,3

0,123456789

© www.soinside.com 2019 - 2024. All rights reserved.