C++, using <chrono>, I would like to get a value formatted as <seconds>.<milliseconds>. I am using system_clock and get the current seconds as:
auto secs = duration_cast<seconds>(tp.time_since_epoch()).count();
How might I get the precision to include milliseconds, so that the result ends up similar to the following with only two decimal places? E.g., 1762452926.34.
2 Answers 2
If you want to stay within the chrono type system a little longer, you could get a little help.
Since you only want two decimal places for fractions of a second, the unit you're after is centiseconds, not milliseconds. chrono doesn't have centiseconds out of the box. But it is a one-liner to create it:
using centiseconds = duration<int64_t, centi>;
Now convert your tp to centiseconds, without using the .count() escape hatch into integers:
auto cs = floor<centiseconds>(tp.time_since_epoch());
You could also choose round or ceil at this point if you wanted to round-to-nearest, or round-up. floor rounds down.
Find out how many whole seconds are in that count:
auto s = floor<seconds>(cs);
Subtract the whole seconds out:
cs -= s;
Now format the seconds and centiseconds manually. Be careful with the case that you have less than 10 centiseconds as you'll need a leading zero.
cout << s.count() << '.';
if (cs < centiseconds{10})
cout << '0';
cout << cs.count() << '\n';
1 Comment
std::println. The following works on godbolt: std::println("{}.{:0>2}", s.count(), cs.count());.In a nutshell:
- get milliseconds.
- calculate number of full seconds represented by those milliseconds.
- calculate how many milliseconds are "left over".
- truncate or round the "leftover milliseconds" to two digits.
- combine and display the result.
As pointed out in comments: "If you choose to round rather than truncate, then step 4 could be too late. If the leftover is something like 996 ms, then rounding to tens of milliseconds would leave you with 1000 ms, and you'd have to carry into the seconds you'd already determined.". So, if rounding is what you want, do it between steps 1 & 2.