📜  C#| Decimal.ToString方法|设置-2

📅  最后修改于: 2021-05-29 22:58:49             🧑  作者: Mango

Decimal.ToString()方法用于将当前实例的数值转换为其等效的字符串表示形式。此方法的重载列表中有4种方法,如下所示:

  • ToString(String)方法
  • ToString()方法
  • ToString(IFormatProvider)方法
  • ToString(String,IFormatProvider)方法

在这里,我们将讨论最后两种方法。

ToString(IFormatProvider)方法

此方法用于使用指定的区域性特定格式信息将当前实例的数值转换为其等效的字符串表示形式。

句法:

public string ToString (IFormatProvider provider);

参数:此方法采用IFormatProvider类型的对象,该对象提供特定于区域性的格式设置信息。

返回值:该方法以provider参数指定的格式返回当前对象的值的字符串表示形式。

例子:

// C# program to demonstrate
// Decimal.ToString(IFormatProvider)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // declaring and initializing
        // Decimal value
        decimal d1 = 568912m;
  
        // creating and initializing
        // the object of CultureInfo
        CultureInfo provider = new CultureInfo("en-us");
  
        // using the method
        string value = d1.ToString(provider);
  
        // Display the value
        Console.WriteLine("The Value is {0} and provider is {1}",
                                           value, provider.Name);
    }
}
输出:
The Value is 568912 and provider is en-US

Decimal.ToString(String,IFormatProvider)方法

此方法用于使用指定的格式和区域性特定的格式设置信息将当前实例的数值转换为其等效的字符串表示形式。

句法:

public string ToString (string format, IFormatProvider provider);

参数:

返回值:该方法以provider参数指定的格式返回当前实例的值的字符串表示形式。

例子:

// C# program to demonstrate the
// Decimal.ToString(String, IFormatProvider)
// Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // declaring and intializing
        // Decimal value
        decimal d1 = 78459995m;
  
        // creating and initializing
        // the object of CultureInfo
        CultureInfo provider = new CultureInfo("fr-FR");
  
        // declaring and intializing format
        string format = "E04";
  
        // using the method
        string val = d1.ToString(format, provider);
  
        // Displaying the details
        Console.WriteLine("The value is {0}",val);
        Console.WriteLine("The Format is {0}",format);
        Console.WriteLine("The Provider is {0}", provider.Name);
    }
}
输出:
The value is 7,8460E+007
The Format is E04
The Provider is fr-FR

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.decimal.tostring?view=netframework-4.7.2