11

If I convert to a coarser unit of time (say std::chrono::minutes to std::chrono::hours) how will duration_cast round? For example, what value will std::chrono::minutes(91) become if converted to std::chrono::hours? 2h, 1h?

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
RichardBruce
  • 641
  • 2
  • 10
  • 19
  • 1
    It shouldn't take much time to write a quick test program, and figure out the answer. – Sam Varshavchik Mar 21 '16 at 02:57
  • 1
    The algorithm is described in [time.duration.cast] (e.g. [here](https://raw.githubusercontent.com/cplusplus/draft/master/papers/n4582.pdf)). – Kerrek SB Mar 21 '16 at 03:02
  • Similar question: https://stackoverflow.com/questions/48468068/whats-the-difference-between-floor-and-duration-cast – Gelldur Jan 24 '19 at 17:52

1 Answers1

12

duration_cast always rounds towards zero. I.e. positive values round down and negative values round up.

For other rounding options see:

http://howardhinnant.github.io/duration_io/chrono_util.html

floor, ceil, and round are currently in the draft C++ 1z (hopefully C++17) draft working paper. In the meantime feel free to use the code at chrono_util.html, and please let me know if you have any problems with it.


C++ 17 update


std::chrono::floor<std::chrono::seconds>(1400ms)  ==  1s
std::chrono::floor<std::chrono::seconds>(1500ms)  ==  1s
std::chrono::floor<std::chrono::seconds>(1600ms)  ==  1s
std::chrono::floor<std::chrono::seconds>(-1400ms) == -2s
std::chrono::floor<std::chrono::seconds>(-1500ms) == -2s
std::chrono::floor<std::chrono::seconds>(-1600ms) == -2s
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577