Skip to content

Commit

Permalink
简化TrimNumber逻辑,改进负号处理
Browse files Browse the repository at this point in the history
移除了 `hasNegativeSign` 变量及其相关逻辑,简化了代码。
修改了负号 `-` 的处理逻辑,现在如果负号出现在非开头位置,函数将返回 0。
更新了字符检查逻辑,确保负号 `-` 也被视为有效字符。
移除了在没有有效数字时返回 0 的逻辑,使函数返回值更加直接。
  • Loading branch information
猿人易 committed Sep 19, 2024
1 parent 937efb7 commit fcdfa9b
Showing 1 changed file with 3 additions and 15 deletions.
18 changes: 3 additions & 15 deletions NewLife.Core/Common/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -633,24 +633,15 @@ public virtual DateTimeOffset ToDateTimeOffset(Object? value, DateTimeOffset def
private static Int32 TrimNumber(ReadOnlySpan<Char> input, Span<Char> output)
{
var rs = 0;
var hasNegativeSign = false;

for (var i = 0; i < input.Length; i++)
{
// 去掉逗号分隔符
var ch = input[i];
if (ch == ',' || ch == '_' || ch == ' ') continue;

// 检查负号
if (ch == '-')
{
if (rs == 0) // 负号只能在开头
{
output[rs++] = ch;
hasNegativeSign = true;
}
continue; // 跳过负号的后续处理
}
// 支持负数
if (ch == '-' && rs > 0) return 0;

// 全角空格
if (ch == 0x3000)
Expand All @@ -659,14 +650,11 @@ private static Int32 TrimNumber(ReadOnlySpan<Char> input, Span<Char> output)
ch = (Char)(input[i] - 0xFEE0);

// 数字和小数点 以外字符,认为非数字
if (ch is not '.' and (< '0' or > '9')) return 0;
if (ch is not '.' and not '-' and (< '0' or > '9')) return 0;

output[rs++] = ch;
}

// 如果没有有效的数字,返回0
if (rs == 0 && !hasNegativeSign) return 0;

return rs;
}

Expand Down

0 comments on commit fcdfa9b

Please sign in to comment.