如果目标只是解析小数,则使用正确设置的NumberStyles的decimal.Parse或decimal.TryParse将满足您的需求。
const NumberStyles numberStyles = NumberStyles.AllowParentheses
| NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint;
decimal parsed;
var successful = decimal.TryParse(s, numberStyles, CultureInfo.CurrentCulture, out parsed);
完整测试:
var values = new[]
{
"1,024.12",
"500.00",
"10,456.23",
"2.89",
"(8,456.15)",
"(1.63)",
"123.1234.12345.123456789.12345.123"
};
const NumberStyles numberStyles = NumberStyles.AllowParentheses
| NumberStyles.AllowThousands
| NumberStyles.AllowDecimalPoint;
var culture = CultureInfo.CurrentCulture;
foreach (var s in values)
{
decimal parsed;
var successful = decimal.TryParse(s, numberStyles, culture, out parsed);
Console.WriteLine("Successful? {0}; Parsed = {1}",
successful,
successful ? parsed.ToString() : "?");
}
输出:
成功的?真的; 已解析 = 1024.12
成功的?真的; 已解析 = 500.00
成功的?真的; 已解析 = 10456.23
成功的?真的; 已解析 = 2.89
成功的?真的; 已解析 = -8456.15
成功的?真的; 已解析 = -1.63
成功的?错误的; 解析 = ?