Search code examples
c#timespan

How to multiply a TimeSpan by a percentage


I'm trying to multiply a TimeSpan by a coefficient, but I don't know how to do it.

i've tried this:

long ErrorCoef = 25;
TimeSpan TotalTimer = new TimeSpan(10,1,2,0);
TimeSpan TotalTimer2 = TimeSpan.FromTicks(TotalTimer.Ticks + TotalTimer.Ticks * (ErrorCoef / 100));

but the (ErrorCoef/100) is automatically Cast as Long, so it returns 0.

(The TimeSpan.FromTicks() method only accepts Long and not Double)


Solution

  • Timespan has a Multiply method so a

    var factor = 1.25d;
    var totalTimer = new TimeSpan(10,1,2,0);
    var totalTimer2 = totalTimer.Multiply(factor);
    

    should do the trick.