c# 如何用时间跨度截断毫秒数?
c# How to truncate milliseconds with timespan?
我想显示一个代表计时器的浮点数,我正在尝试将其格式化为:
00:00:00 (Minutes:Seconds:Milliseconds)
public static string ConvertToTime(float t){
TimeSpan ts = TimeSpan.FromSeconds(t);
return string.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds);
}
但这会给出完整的毫秒数,即使我用 00 定义格式也不会降低精度。
For example if the timer is 3.4234063f it should output 00:03:42 not 00:03:423.
这么基础的东西,我用timespan的时候解决不了
当您只需要一些简单的数学运算时,请不要使用 TimeSpan
。
像这样的东西(未经测试)避免分配并完成你想要的。
public static string ConvertToTime(float t){
int totalSeconds = (int)t;
int minutes = totalSeconds / 60;
int seconds = totalSeconds % 60;
int hundredthsOfASecond = (int)((t - totalSeconds)*100);
return $"{minutes:00}:{seconds:00}.{hundredthsofASecond:00}";
}
为了您的用户的理智,我建议您将时间显示为 mm:ss.ss
,其中秒数显示为小数点后两位。
这样做:
public static string ConvertToTime(float t)
{
return string.Format("{0:00}:{1:00.00}", t/60, t%60);
}
我想显示一个代表计时器的浮点数,我正在尝试将其格式化为:
00:00:00 (Minutes:Seconds:Milliseconds)
public static string ConvertToTime(float t){
TimeSpan ts = TimeSpan.FromSeconds(t);
return string.Format("{0:00}:{1:00}:{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds);
}
但这会给出完整的毫秒数,即使我用 00 定义格式也不会降低精度。
For example if the timer is 3.4234063f it should output 00:03:42 not 00:03:423.
这么基础的东西,我用timespan的时候解决不了
当您只需要一些简单的数学运算时,请不要使用 TimeSpan
。
像这样的东西(未经测试)避免分配并完成你想要的。
public static string ConvertToTime(float t){
int totalSeconds = (int)t;
int minutes = totalSeconds / 60;
int seconds = totalSeconds % 60;
int hundredthsOfASecond = (int)((t - totalSeconds)*100);
return $"{minutes:00}:{seconds:00}.{hundredthsofASecond:00}";
}
为了您的用户的理智,我建议您将时间显示为 mm:ss.ss
,其中秒数显示为小数点后两位。
这样做:
public static string ConvertToTime(float t)
{
return string.Format("{0:00}:{1:00.00}", t/60, t%60);
}