C# String Format for hours and minutes from decimal

前端 未结 3 1128
盖世英雄少女心
盖世英雄少女心 2020-12-17 15:09

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 d

3条回答
  •  天涯浪人
    2020-12-17 15:56

    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.

提交回复
热议问题