Skip to content

TimeSpan.Parse gives inconsistent and incorrect results with 8 fractional digits #27947

Closed
@pengowray

Description

@pengowray

I've made my own TimeSpanParser and have been testing it against System.TimeSpan.Parse() and have come up with some issues with TimeSpan.Parse(string)

In brief, all these tests pass successfully:

Assert.AreEqual(TimeSpan.Parse("0:00:00.0123456"),
                TimeSpan.Parse("0:00:00.00123456"));
Assert.AreEqual(TimeSpan.Parse("0:00:00.0123456").Ticks,  123456);
Assert.AreEqual(TimeSpan.Parse("0:00:00.00123456").Ticks, 123456);

For more examples, here's a walk-through of this issue:
https://github.com/quole/TimeSpanParser/blob/master/TimeParser.Tests/NotWrittenHereUnderflowWeirdnessTests.cs

TimeSpan.Parse() allows seconds with up to 7 decimal places, which is perfect to let you specify a duration down to a tick (100ns). At 9 decimal places it sensibly throws OverflowExceptions. But in between 7 and 9 it's the twilight zone, where you'll find bizarre inconsistent and incorrect results.

I'm guessing the check for "underflows" is off by one decimal place, and is meant to throw an OverflowException for all 8 decimal place numbers, but instead only does it consistently around 9.

Suggestions:

  • Not sure how you can fix this without breaking existing code.
  • At the least, TimeSpan.Parse() ought to ignore trailing zeros after the decimal place (and definitely shouldn't cause the result to be multiplied by 10)

I couldn't find any related reports. Is this really a new issue?

Tested on net core 2.0 & 2.2

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions