📅  最后修改于: 2023-12-03 15:00:14.563000             🧑  作者: Mango
在 C# 中,Convert.ToDecimal(String, IFormatProvider) 方法用于将指定字符串表示形式的数字转换为等效的十进制数,其中使用指定的区域性特定格式和格式提供程序格式。
public static decimal ToDecimal(string value, IFormatProvider provider);
一个表示十进制数字的对象。
下面是 Convert.ToDecimal(String, IFormatProvider) 方法的一些示例。
using System;
using System.Globalization;
public class Example {
public static void Main() {
string[] values = { "123456789", "12345.6789", "-12345.6789",
"1234567890.1234567890", "123456789012345678901234567890" };
CultureInfo[] cultures = { CultureInfo.InvariantCulture,
new CultureInfo("en-US"),
new CultureInfo("fr-FR"),
new CultureInfo("es-ES") };
foreach (string value in values) {
foreach (CultureInfo culture in cultures) {
try {
decimal number = Convert.ToDecimal(value, culture);
Console.WriteLine("{0}, {1}: {2}",
value, culture.Name, number);
}
catch (FormatException) {
Console.WriteLine("{0}, {1}: Bad Format",
value, culture.Name);
}
catch (OverflowException) {
Console.WriteLine("{0}, {1}: Overflow",
value, culture.Name);
}
}
Console.WriteLine();
}
}
}
123456789, invariant language (Invariant Country): 123456789
123456789, en-US: 123456789
123456789, fr-FR: 123456789
123456789, es-ES: 123456789
12345.6789, invariant language (Invariant Country): 12345.6789
12345.6789, en-US: 12345.6789
12345,6789, fr-FR: 12345.6789
12345,6789, es-ES: Bad Format
-12345.6789, invariant language (Invariant Country): -12345.6789
-12345.6789, en-US: -12345.6789
-12345,6789, fr-FR: -12345.6789
-12345,6789, es-ES: -12345.6789
1234567890.1234567890, invariant language (Invariant Country): 1234567890.123456789
1234567890.1234567890, en-US: 1234567890.1234568
1234567890,1234567890, fr-FR: 1234567890.123456789
1234567890,1234567890, es-ES: 1234567890.123456789
123456789012345678901234567890, invariant language (Invariant Country): Overflow
123456789012345678901234567890, en-US: Overflow
123456789012345678901234567890, fr-FR: Overflow
123456789012345678901234567890, es-ES: Overflow
Convert.ToDecimal(String, IFormatProvider) 方法是将字符串转换为等效十进制数的一种简便方法。通过提供特定于区域性的格式信息,可以确保在不同语言和区域设置中,字符串能够正确地转换为十进制数。在实现过程中,请确保始终为您的代码提供适当的异常处理,以处理字符串无法转换为十进制数以及超出十进制范围的情况。