c++ - 将 uint64_t 转换为 double 时调整精度

标签 c++ double precision

我有一个方法以下列格式返回时间的字符串表示形式:_HH:MM:SS.sss 该方法采用以微秒为单位的 uint64_t 时间作为参数。我可以很容易地划分小时和分钟,但是当涉及到秒时,我需要转换为 double ,这样我也可以获得秒的小数部分。

示例代码:

std::string getDurationTime(uint64_t time){

  std::string returnTime="";

   uint64_t tempTime = time;
   uint64_t hours = (tempTime / 3600000000);
   tempTime -= (hours * 3600000000);

   uint64_t minutes = (tempTime / 60000000);
   tempTime -= (minutes * 60000000);

   double seconds = (double(tempTime) / 1000000);

   stringstream timeOut;

   timeOut<<std::setw(2)<<std::setfill('0')<<hours<<":"<<std::setw(2)<<std::setfill('0')<<minutes<<":"<<std::fixed<<std::setw(6)<<std::setprecision(3)<<std::setfill('0')<<seconds;

  returnTime = "_" + timeOut.str();

  return returnTime;

}

所以像 103566 这样的数字应该返回值 _00:00:00:104,但它返回的是 _00:00:00:103。当我在秒上设置断点时,该值为 0.103499999。是否有用于调整此精度的标准技术?如果我将 .000001 添加到结果秒数中,它每次都能解决该精度的问题吗?

感谢任何建议。

最佳答案

您可以使用 seconds = round(seconds * 1000.0)/1000.0; 将您的数字四舍五入为每秒几千。

关于c++ - 将 uint64_t 转换为 double 时调整精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14325096/

相关文章:

math - float 学坏了吗?

c++ - Printf 函数格式化程序

c++ - g++编译错误: `.rodata' can not be used when making a shared object; recompile with -fPIC

c++ - 计算飞行距离的程序

java - 为什么 Double.infinite 不为无限分数返回 true?

c++ - C++ 可以在内部表示而无需舍入的 0 和 1 之间的最大和最小数字是多少?

c++ - 将 double 从文本文件转换为二进制文件

c++ - 对本周大师的理解 #67 : Double or Nothing

python - 如何在 ~100-200us 进行延迟

c++ - 来自类型库堆或堆栈的 com 对象