C#中decimal.TryParse解析12.3为何被视为123?改12,3正常的原因
字符串数字求和解析异常的原因及解决办法
问题重现
你遇到的情况是:字符串数组中的"12.3"被解析为123,最终求和结果为179;将"12.3"改为"12,3"后,解析和计算恢复正常。相关代码与输出如下:
原代码
string[] values = { "12.3", "45", "ABC", "11", "DEF" }; decimal total = 0m; string letters = ""; for (int i = 0; i < values.Length; i++) { string value = values[i]; decimal number; if (decimal.TryParse(value, out number)) { total += number; } else { letters += value; } } Console.WriteLine($"Message: {letters}\nTotal: {total}");
原输出
Message: ABCDEF Total: 179
原因分析
问题核心在于decimal.TryParse的区域文化默认解析规则:
TryParse默认采用当前操作系统的区域设置(CultureInfo)解析数字字符串。- 如果你的系统区域属于用逗号作为小数点分隔符、点作为千位分隔符的地区(如欧洲多数国家),那么
"12.3"里的点会被当作千位分隔符直接忽略,数字被合并为123,最终求和123+45+11=179。 - 改成
"12,3"后,逗号匹配了系统区域的小数点规则,所以能正确解析为12.3,求和结果也恢复正常。
解决办法
如果想让代码不受系统区域影响,或固定解析特定格式的数字,可指定解析时的文化信息:
方法1:使用不变文化(InvariantCulture)
不变文化固定以点作为小数点,适用于处理通用格式的数字字符串:
// 需要引用System.Globalization命名空间 if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out number)) { total += number; }
方法2:指定目标区域文化
如果明确要解析特定区域格式的数字,比如法语区(逗号做小数点):
var frCulture = new CultureInfo("fr-FR"); if (decimal.TryParse(value, NumberStyles.Any, frCulture, out number)) { total += number; }
修改后代码示例(使用不变文化)
using System.Globalization; string[] values = { "12.3", "45", "ABC", "11", "DEF" }; decimal total = 0m; string letters = ""; for (int i = 0; i < values.Length; i++) { string value = values[i]; decimal number; if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out number)) { total += number; } else { letters += value; } } Console.WriteLine($"Message: {letters}\nTotal: {total}");
修改后输出
Message: ABCDEF Total: 68.3
内容的提问来源于stack exchange,提问作者user23712482
相关产品推荐
相关产品推荐

