当我从netcoreapp2.1升级到netcoreapp3.1时,我发现我的一些单元测试失败了。
以下代码具有不同的结果:
using System;
namespace ConsoleApp12
{
class Program
{
static void Main(string[] args)
{
var seconds = 0.81960;
var timeSpan = TimeSpan.FromSeconds(seconds);
Console.WriteLine($"seconds:{seconds}");
Console.WriteLine($"timeSpan:{timeSpan}");
Console.WriteLine($"timeSpan.Milliseconds:{timeSpan.Milliseconds}");
Console.WriteLine($"timeSpan.Ticks:{timeSpan.Ticks}");
}
}
}
/*
core 2.1 and Framework 4.8 ROUNDS to nearest ms
seconds:0.8196
timeSpan:00:00:00.8200000
timeSpan.Milliseconds:820
timeSpan.Ticks:8200000
*/
/*
core 3.1 no longer rounds to nearest ms
seconds:0.8196
timeSpan:00:00:00.8196000
timeSpan.Milliseconds:819
timeSpan.Ticks:8196000
*/这不是显示格式问题,您可以从ticks的底层值中看出这一点。
为什么它们在dotnet核心版本之间是不同的?
发布于 2020-04-14 12:00:12
在dotnet核心2.1和3.1 (大约2019年底)之间,System.TimeSpan changed的行为,使得factory methods不再舍入到最接近的1ms。
这个here有一个github的问题。
注意:当前文档尚未更新以反映行为的变化,示例代码的输出现在在网站上是不正确的:System.TimeSpan.FromSeconds。
在.net核心2.1和Net框架中,创建的TimeSpan将舍入为最接近的ms:
FromSeconds TimeSpan
----------- --------
0.001 00:00:00.0010000
0.0015 00:00:00.0020000
12.3456 00:00:12.3460000
123456.7898 1.10:17:36.7900000
1234567898.7654 14288.23:31:38.7650000
1 00:00:01
60 00:01:00
3600 01:00:00
86400 1.00:00:00
1801220.2 20.20:20:20.2000000 在.net核心3.1中,不会四舍五入到最接近的ms (例如12.3456):
FromSeconds TimeSpan
----------- --------
0.001 00:00:00.0010000
0.0015 00:00:00.0015000
12.3456 00:00:12.3455999
123456.7898 1.10:17:36.7898000
1234567898.7654 14288.23:31:38.7654000
1 00:00:01
60 00:01:00
3600 01:00:00
86400 1.00:00:00
1801220.2 20.20:20:20.2000000https://stackoverflow.com/questions/60987108
复制相似问题