C#字符串格式为十进制小时和分钟字符串、格式为、小时、十进制

2023-09-03 02:30:50 作者:做人上人

有一个简单的字符串格式,将采取十进制重新presenting小时的时间分数并显示为小时和分钟?

例如:5.5的格式来显示5小时30分

我很高兴c写自己的$ C $,但将preFER使用现有功能(如果可用)

解决方案

 十进制T = 5.5M;
Console.WriteLine(TimeSpan.FromHours((双)T)的ToString());
 

这会给你五时30分00秒,这是pretty的接近。然后,您可以格式化你想要的结果:

  VAR TS = TimeSpan.FromHours((双)T);
Console.WriteLine({0}小时{1}分钟,ts.Hours,ts.Minutes);
 
第3章 9 字符串转换成十进制整数 15 分

请注意,有一个用于精确的从十进制两倍的转换损失的潜力,但我不认为这将是明显的分钟刻度。有人用型系统的双向飞碟状的理解也许能在这里磬。

Is there a simple string format that will take a decimal representing hours and fractions of hours and show it as hours and minutes?

For example : 5.5 formatted to display 5 hrs 30 minutes.

I am happy to write the code myself, however would prefer to use existing functionality if it is available

解决方案

decimal t = 5.5M;
Console.WriteLine(TimeSpan.FromHours((double)t).ToString());

That'll give you "05:30:00" which is pretty close. You could then format that to your desired result:

var ts = TimeSpan.FromHours((double)t);
Console.WriteLine("{0} hrs {1} minutes", ts.Hours, ts.Minutes);

Note that there's a potential for loss of accuracy in the conversion from decimal to double, but I don't think it would be noticeable on the minute scale. Someone with a Skeet-like understanding of the type system might be able to chime in here.