Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit f548465

Browse files
committed
Parse plus and trailing zeroes in exponent
1 parent d8ed1fd commit f548465

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/ServiceStack.Text/Support/StringSegmentExtensions.cs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -472,7 +472,7 @@ public static decimal ParseDecimal(this StringSegment value, bool allowThousands
472472
state = ParseState.TrailingWhite;
473473
} else if (c == 'e' || c == 'E')
474474
{
475-
if (noIntegerPart && scale == 0.1m)
475+
if (noIntegerPart && scale == 0)
476476
throw new FormatException(BadFormat);
477477
state = ParseState.Exponent;
478478
} else if (c >= '0' && c <= '9')
@@ -500,9 +500,33 @@ public static decimal ParseDecimal(this StringSegment value, bool allowThousands
500500
}
501501
break;
502502
case ParseState.Exponent:
503-
if (c == '-' || (c >= '0' && c <= '9'))
503+
bool expNegative = false;
504+
if (c == '-')
505+
{
506+
if (i == end)
507+
throw new FormatException(BadFormat);
508+
509+
expNegative = true;
510+
c = value.Buffer[i++];
511+
}
512+
else if (c == '+')
504513
{
505-
var exp = (sbyte)- new StringSegment(value.Buffer, i - 1, end - i + 1).ParseSByte();
514+
if (i == end)
515+
throw new FormatException(BadFormat);
516+
c = value.Buffer[i++];
517+
}
518+
519+
//skip leading zeroes
520+
while (c == '0' && i < end) c = value.Buffer[i++];
521+
522+
if (c > '0' && c <= '9')
523+
{
524+
var exp = new StringSegment(value.Buffer, i - 1, end - i + 1).ParseSByte();
525+
if (!expNegative)
526+
{
527+
exp = (sbyte) -exp;
528+
}
529+
506530
if (exp >= 0 || scale > -exp)
507531
{
508532
scale += exp;

tests/ServiceStack.Text.Tests/Support/StringSegmentParse.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ public void Can_parse_decimal()
6767
Assert.That(new StringSegment("10.001E-2").ParseDecimal(), Is.EqualTo(0.10001m));
6868
Assert.That(new StringSegment("10.001e-8").ParseDecimal(), Is.EqualTo(0.00000010001m));
6969
Assert.That(new StringSegment("2.e2").ParseDecimal(), Is.EqualTo(200m));
70-
//Assert.Throws<FormatException>(() => new StringSegment(".e2").ParseDecimal());
70+
Assert.Throws<FormatException>(() => new StringSegment(".e2").ParseDecimal());
71+
Assert.That(new StringSegment("9.e+000027").ParseDecimal(), Is.EqualTo(decimal.Parse("9.e+000027", NumberStyles.Float, CultureInfo.InvariantCulture)));
7172

7273
//allow thouthands
7374
Assert.That(new StringSegment("1,234.5678").ParseDecimal(true), Is.EqualTo(1234.5678m));

0 commit comments

Comments
 (0)