5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

誤差なくTimeSpanを作る

Posted at

参考

この記事は、以下の動画を参考にしています。
詳しくは、動画をご覧ください。

.NET 8まで

秒数(など)からTimeSpanを作る場合、元となるdoubleが誤差を含む可能性があり、TimeSpanにも誤差が付いてしまう。

var time = TimeSpan.FromSeconds(value: 101.832);
Console.WriteLine(time);
// 00:01:41.8319999

.NET 9

TimeSpan.FromSecondsには、秒、ミリ秒、マイクロ秒をそれぞれlongで指定するオーバーロードが用意されており、誤差なくTimeSpanを作ることができる。

var time = TimeSpan.FromSeconds(seconds: 101, milliseconds: 832);
Console.WriteLine(time);
// 00:01:41.8320000

TimeSpan.FromMinutesなど、他のメソッドにも同様のオーバーロードが用意されている。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?