为什么TimeSpan.FromSeconds(双)轮毫秒?TimeSpan、FromSeconds

2023-09-02 23:49:26 作者:就算难过那么深邃▍▏

TimeSpan.FromSeconds 需要加倍,并且可以重新present值下降到100纳秒,但是这种方法莫名其妙地舍入的时候整个毫秒。

由于我刚刚花了一个半小时,以找出这个(证明!)的行为,知道为什么会出现这种情况会更容易忍受的浪费的时间。

任何人都可以说明为什么这个看似适得其反的行为实施?

  TimeSpan.FromSeconds(0.12345678).TotalSeconds
    // 0.123
TimeSpan.FromTicks((长)(TimeSpan.TicksPerSecond * 0.12345678))。TotalSeconds
    // 0.1234567
 

解决方案

正如你已经找到了自己,这是一个记录的功能。它的时间跨度的文档中描述的:

  

参数

     

值的类型:System.Double

     

若干秒,精确到毫秒

这样做的原因可能是因为双不是准确的。它始终是一个好主意比较双打的时候做一些舍入,因为它可能只是一个非常小的位大于或小于你所期望的。当你试图把全部毫秒为单位的行为实际上可以为你提供一些意想不到的纳秒。我认为这是他们选择了舍入值,以毫秒为单位整并丢弃较小的数字的原因。

TimeSpan.FromSeconds takes a double, and can represent values down to 100 nanoseconds, however this method inexplicably rounds the time to whole milliseconds.

java中如何将Timestamp转换为毫秒数

Given that I've just spent half an hour to pinpoint this (documented!) behaviour, knowing why this might be the case would make it easier to put up with the wasted time.

Can anyone suggest why this seemingly counter-productive behaviour is implemented?

TimeSpan.FromSeconds(0.12345678).TotalSeconds
    // 0.123
TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond * 0.12345678)).TotalSeconds
    // 0.1234567

解决方案

As you've found out yourself, it's a documented feature. It's described in the documentation of TimeSpan:

Parameters

value Type: System.Double

A number of seconds, accurate to the nearest millisecond.

The reason for this is probably because a double is not that accurate at all. It is always a good idea to do some rounding when comparing doubles, because it might just be a very tiny bit larger or smaller than you'd expect. That behaviour could actually provide you with some unexpected nanoseconds when you try to put in whole milliseconds. I think that is the reason they chose to round the value to whole milliseconds and discard the smaller digits.