Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duration seconds to nanoseconds is not precise #1434

Closed
EddyHaigh opened this issue Nov 21, 2024 · 2 comments
Closed

Duration seconds to nanoseconds is not precise #1434

EddyHaigh opened this issue Nov 21, 2024 · 2 comments

Comments

@EddyHaigh
Copy link

Describe the bug
Using UnitsNet.Duration.FromSeconds(1).Nanoseconds produces 999999999.9999999 which not precise compared to other similar down scaled conversions for duration e.g. ms, µs.

To Reproduce
Steps to reproduce the behavior:

  1. Add nuget UnitsNet 5.60.0 to a .NET 8.0 project
  2. Build using Visual Studio 2022 Community v17.12.1
  3. In a ConsoleApp write UnitsNet.Duration.FromSeconds(1).Nanoseconds to the console

Expected behavior
Nanoseconds produced from converting from seconds should produce 1000000000 rather than losing precision

Screenshots
image

Additional context
The normal TimeSpan (TimeSpan.FromSeconds(1).TotalNanoseconds) contains a more accurate nanoseconds

@EddyHaigh EddyHaigh added the bug label Nov 21, 2024
@lipchev
Copy link
Collaborator

lipchev commented Nov 21, 2024

Hi @EddyHaigh,

this is a known limitation of the current implementation: having a double as the underlying value type, the conversions often introduce a small rounding error. Here's a quote that we should have probably added to the wiki page long ago:

The double data type in C# uses a binary floating-point representation, which complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

Hopefully this won't be required with my upcoming proposition for replacing the doubles (the PR should be out this weekend).

Until such version is release, you should consider using ToString directly on the Duration itself, this should round-off the problem (you can specify the precision using the format specifier: e.g. "G4")

Copy link

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants