Skip to content

Commit

Permalink
类型转换要支持负数
Browse files Browse the repository at this point in the history
  • Loading branch information
猿人易 committed Sep 19, 2024
1 parent a36923a commit 937efb7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
16 changes: 16 additions & 0 deletions NewLife.Core/Common/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -633,12 +633,25 @@ 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 == 0x3000)
ch = (Char)0x20;
Expand All @@ -651,6 +664,9 @@ private static Int32 TrimNumber(ReadOnlySpan<Char> input, Span<Char> output)
output[rs++] = ch;
}

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

return rs;
}

Expand Down
9 changes: 9 additions & 0 deletions XUnitTest.Core/Common/UtilityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,4 +282,13 @@ public void UtcTime()
//Assert.NotEqual(str, time.ToLocalTime().ToFullString());
//Assert.NotEqual(str, time.ToUniversalTime().ToFullString());
}

[Fact]
public void NegativeNumber()
{
var n = "-1";
var v = n.ToInt();

Assert.Equal(-1, v);
}
}

0 comments on commit 937efb7

Please sign in to comment.