Nullable int区域性特定于toString()

时间:2019-04-25 11:13:32

标签: c# int tostring long-integer cultureinfo

我有一个int和可为null的int变量,我想使用一种特定的区域性格式将它们转换为字符串,即用点将数字分开。

var culture = CultureInfo.CreateSpecificCulture("de-DE");
int contactSum = 123456;
int? resultSum = 654321;

对于int,我可以执行以下操作:

Console.WriteLine($"The contact sum was: {contactSum.ToString("N0", culture)}");

这将输出以下内容

  

联系方式为:123.456

Nullable int但是没有格式重载。如何以与int相同的方式设置可为null的int格式?还是有更好的方法来进行这种格式设置?

最终结果如下:

  

结果总和是:654.321

2 个答案:

答案 0 :(得分:2)

这是您实现目标的两种不同方式。

var culture = CultureInfo.CreateSpecificCulture("de-DE");
int contactSum = 123456;
int? resultSum = 654321;
Console.WriteLine($"The contact sum was: {contactSum.ToString("N0", culture)}");
Console.WriteLine($"The contact sum was: {resultSum?.ToString("N0", culture)}");
Console.WriteLine($"The contact sum was: {(resultSum.HasValue ? resultSum.Value.ToString("N0", culture) : "NULL")}");

答案 1 :(得分:2)

一种更优雅的书写方式:

  1. 指定要用作占位符一部分的格式
  2. 将插值字符串文字存储为FormattableString,然后在整个字符串上使用ToString(),以指定在解释字符串时使用的区域性。

示例代码

private void Test(object sender, EventArgs e)
{
    int contactSum = 123456;
    int? resultSum = 654321;
    int? nullSum = null;

    CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");

    ShowInt(contactSum, culture);
    ShowInt(resultSum, culture);
    ShowInt(nullSum, culture);

    culture = CultureInfo.CreateSpecificCulture("de-DE");

    ShowInt(contactSum, culture);
    ShowInt(resultSum, culture);
    ShowInt(nullSum, culture);
}

private void ShowInt(int? value, IFormatProvider formatProvider)
{
    FormattableString message = $"The Sum was: {value:N0}";
    Console.WriteLine(message.ToString(formatProvider));
}

输出:

The Sum was: 123,456
The Sum was: 654,321
The Sum was: 
The Sum was: 123.456
The Sum was: 654.321
The Sum was: