angularsen / UnitsNet

Makes life working with units of measurement just a little bit better.
https://www.nuget.org/packages/UnitsNet/
MIT No Attribution
2.65k stars 382 forks source link

Duration seconds to nanoseconds is not precise #1434

Open EddyHaigh opened 2 days ago

EddyHaigh commented 2 days ago

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

lipchev commented 2 days ago

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")