Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to control the displayed precision when sending `std::chrono::locale_time` to a c++ stream?

I’m almost happy with this:

const auto time = std::chrono::current_zone()->to_local(std::chrono::system_clock::now());
std::cout << time;

It prints:

2023-07-26 21:08:47.2889025

that’s great, but I’d like it to print slightly less decimals, for instance:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2023-07-26 21:08:47.289

Is there some iomanip-like ways of specifying the desired precision?
Something like:

std::cout << std::chrono::setprecision(3) << time;

>Solution :

Just floor it to milliseconds, either when you call now, or when you store it, or when you print it:

const auto time = std::chrono::current_zone()->to_local(std::chrono::system_clock::now());
std::cout << std::chrono::floor<std::chrono::milliseconds>(time);

Or use round or ceil depending on your rounding preference.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading