https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114244
Bug ID: 114244
Summary: Need to use round when parsing fractional seconds
Product: gcc
Version: 14.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: libstdc++
Assignee: unassigned at gcc dot gnu.org
Reporter: howard.hinnant at gmail dot com
Target Milestone: ---
I'm not sure if this is a bug or just QOI. But consider:
#include <chrono>
#include <string>
#include <iostream>
using time_point_t = std::chrono::sys_time<std::chrono::milliseconds>;
time_point_t decrypt(std::string s) {
time_point_t tp;
std::istringstream in(s);
in >> parse("%Y%m%d-%T", tp);
return tp;
}
int main() {
std::cout << decrypt("20240304-13:00:00.002");
}
I expect the output to be:
2024-03-04 13:00:00.002
but it is:
2024-03-04 13:00:00.001
I believe the issue is the use of duration_cast<milliseconds> or
time_point_cast<milliseconds> somewhere under the parse (not sure exactly
where). Since 0.002 is not exactly representable in floating point, we're
getting a truncate towards zero because this parses as just barely under 0.002.
I highly recommend the use of round<Duration> when converting floating point
based durations and time_points to integral based.