C#中统计decimal类型小数点后首个非零数字前的零的个数
统计decimal数值小数点后首个非零数字前的零的个数
你的现有实现依赖字符串拆分特定数字,通用性很差(比如换个非1结尾的数就失效),而且效率也不高。下面提供两种更可靠高效的实现方式:
方法一:利用decimal精确运算(推荐)
decimal是精确小数类型,直接通过数值运算统计,避免字符串转换的开销和潜在格式问题:
int CountLeadingZerosAfterDecimal(decimal value) { value = Math.Abs(value); var fractional = value - Math.Floor(value); if (fractional == 0) return 0; int count = 0; while (fractional < 1) { fractional *= 10; if (Math.Floor(fractional) == 0) count++; else break; } return count; } // 测试示例 decimal test1 = 0.001m; Console.WriteLine(CountLeadingZerosAfterDecimal(test1)); // 输出2 decimal test2 = 0.000789m; Console.WriteLine(CountLeadingZerosAfterDecimal(test2)); // 输出3 decimal test3 = 5.6m; Console.WriteLine(CountLeadingZerosAfterDecimal(test3)); // 输出0
方法二:通用字符串处理法
如果偏好字符串操作,改用更通用的遍历逻辑,不依赖特定数字:
int CountLeadingZerosAfterDecimal(decimal value) { // 用固定文化避免小数点格式差异(比如某些地区用逗号) var str = value.ToString(System.Globalization.CultureInfo.InvariantCulture); int dotPos = str.IndexOf('.'); if (dotPos == -1) return 0; int count = 0; for (int i = dotPos + 1; i < str.Length; i++) { if (str[i] == '0') count++; else break; } return count; }
原实现的问题
原代码通过Split('1')截断字符串,一旦输入的数不是以1结尾(比如0.002m),结果就完全错误;而且Split操作会生成额外的字符串数组,效率不如直接遍历或数值运算。
内容的提问来源于stack exchange,提问作者Kababum
相关产品推荐
相关产品推荐

