C#字符串格式为十进制小时和分钟 [英] C# String Format for hours and minutes from decimal

查看:190
本文介绍了C#字符串格式为十进制小时和分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的字符串格式,将采取十进制重新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);
 

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

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.

这篇关于C#字符串格式为十进制小时和分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆