TimeSpan中的TotalMinutes只有2位小数

问题描述 投票:0回答:2

我需要在TimeSpan中获得TotalMinutes只有2位小数,2位小数指的是小数不应超过59的秒数。如果超过,则将添加整数。例如:

1.59

1分59秒,如果增加一秒,则计为分钟

2.00

我在下面尝试了以下代码:

var a_sec: float = 0.0;
var a_dec: float = 0.0;

a_sec= TimeSpan.Parse(add).TotalMinutes;
a_dec=Math.Round(a_sec,2);

但这不适用于我的,错误显示:对象不支持此属性或方法。

c# timespan
2个回答
1
投票

我觉得类似的东西

string.Format("{0:0}.{1:00}", Math.Truncate(ts.TotalMinutes), ts.Seconds);

会工作。


0
投票

下面是如何将Minutes in double(小数部分0-99)转换为Real Minutes(小数部分0-59)的示例:

public class Program
{
    public static void Main(string[] args)
    {
        //Your code goes here
        TimeSpan a = TimeSpan.FromMinutes(2);
        TimeSpan b = TimeSpan.FromMinutes(1.95);
        TimeSpan c = TimeSpan.FromMinutes(1.97);
        TimeSpan d = TimeSpan.FromMinutes(1.99);

        Console.WriteLine(GetRealMinutesDouble(a));   // out - 2
        Console.WriteLine(GetRealMinutesDouble(b));   // out - 1,57
        Console.WriteLine(GetRealMinutesDouble(c));   // out - 1,58
        Console.WriteLine(GetRealMinutesDouble(d));   // out - 1,59
    }
    public static double GetRealMinutesDouble(TimeSpan a )
    {
        var aSecondsPart = a.TotalMinutes - Math.Truncate(a.TotalMinutes);// Cut the decimal part which shows the seconds
        var aSecondsPartInRealSeconds = Math.Round(aSecondsPart*60/100*100)/100;// convert them to the interval 0-59
        return Math.Truncate(a.TotalMinutes)+aSecondsPartInRealSeconds;//add them back
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.