Someone stole my minute :/

c#, time, timespan

Solution

Since `0.4` cannot be exactly represented in the `Double` floating-point format, you get its nearest representation, which in the case of `(23.4-23)*100` is probably something like `39.999999999999858`. When you use `(int)`, you truncate the fraction, leaving you with 39.

You need to round instead of truncate, so use `(int)Math.Round(minute)`.

Alternatively, you can use the `Decimal` type, which can exactly represent decimal numbers like `23.40`.

Problem

I am trying to convert a time represented in double, something like `23.40` which means 23 hours and 40 minutes, using the following method: ``` private TimeSpan DoubleToTimeSpan(double time) { double hour = Math.Floor(time); double minute = (time - hour) * 100d; TimeSpan ts = new TimeSpan((int)hour, (int)minute, 0); return ts; } ``` When testing it on some times, like `23.40` for example: ``` Console.WriteLine(DoubleToTimeSpan(23.40)); ``` It shows `23:39:00`, a whole minute has been stolen by the system! Where is my minute? Note: I know about `TimeSpan.FromHours`, this doesn't help me because this method considers the minutes as percentage, so `23.40` is 23 hours and 40% of an hour, which is `23:24:00`.

Original source