将秒转换为小时、分钟、秒.百分之一秒
Convert seconds to hours, minutes, seconds.hundreths of a second
我有一个包含秒数的双精度值,可能是负数,我想要一个格式为 H:mm:ss.hhh 或 -H:mm:ss.hhh 的字符串
std::string getFormattedTime(double seconds)
{
// magic voodoo
}
如果小时为零,我将需要省略小时。
我已经两次遇到各种舍入和精度问题,所以我认为是时候寻求帮助了:)
std::string getLabelForPosition(double seconds)
{
bool negative = seconds < 0.0;
if (negative)
seconds *= -1.0;
double mins = std::floor(std::round(seconds) / 60.0);
double secs = seconds - mins * 60.0;
std::stringstream s;
if (negative)
s << "-";
s << mins << ":" << std::fixed << std::setprecision(decimalPlaces) << secs;
return s.str();
}
让我知道这是否适合您。我敢打赌有一种更简单的方法。
std::string getFormattedTime(double seconds)
{
double s(fabs(seconds));
int h(s/3600);
int min(s/60 - h*60);
double sec(s - (h*60 + min)*60);
std::ostringstream oss;
oss<<std::setfill('0')<<std::setw(2)<<fabs(seconds)/seconds*h<<":"<<std::setw(2)<<min<<":";
if (sec/10<1)
oss<<"0";
oss<<sec;
return oss.str().c_str();
}
这是一个使用boost的解决方案。 假设您有boost::uint64_t secondsSinceEpoch
表示自纪元以来的秒数(我个人不明白您在这种情况下使用双精度的想法,抱歉(。 然后要获得字符串表示形式,只需使用boost::posix_time::to_simple_string(secondsSinceEpoch);
std::string getLabelForPosition(double doubleSeconds)
{
int64 msInt = int64(std::round(doubleSeconds * 1000.0));
int64 absInt = std::abs(msInt);
std::stringstream s;
if (msInt < 0)
s << "-";
auto hours = absInt / (1000 * 60 * 60);
auto minutes = absInt / (1000 * 60) % 60;
auto secondsx = absInt / 1000 % 60;
auto milliseconds = absInt % 1000;
if (hours > 0)
s << std::setfill('0')
<< hours
<< "::";
s << minutes
<< std::setfill('0')
<< ":"
<< std::setw(2)
<< secondsx
<< "."
<< std::setw(3)
<< milliseconds;
return s.str();
}
这几乎是正确的。 实际实现使用缓存来避免在屏幕重新呈现时重新执行所有操作。
相关文章:
- 我应该使用什么来代替void作为变体中的替代类型之一
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- Boost::posix_time::ptime舍入到给定的分钟数
- 填孔方法需要20分钟以上
- 提升,以分钟精度获得 UTC 时间
- 模板化类如何解析在其类型之一上调用的重载非成员函数?
- 如何将 std::filesystem::p ath 转换为 LPCSTR,以便在 LoadLibrary() 变体之一
- 对于使用高级服务的分钟数和应付金额,我不断得到相同的数字
- C++ 一个函数,可以根据接受的值返回两种类型之一
- 有没有简单的方法可以将"02:00"转换为分钟,比如 120?
- 当结构在C++中也被引用时,它是否可以返回其成员之一?
- 输出一个数字,该数字可能是三种类型之一
- 我们如何重新制作程序以打开xml文件并在价格单词之后读取百分比值并更改此值
- gtest:检查字符串是否等于两个字符串之一
- 我在生成返回为数不多的模板化参数之一cpp的函数时遇到问题
- 设计自己的结果/两者之一:是否应该始终指定成功类型和错误类型
- 当C++类函数参数之一是结构时,它们的语法有什么不同
- 将秒转换为小时、分钟、秒.百分之一秒
- 如何使用 pthreads 以正确的方式设置两个线程之一的优先级
- 将十进制的舍入到第十位,但在C 中显示了百分之一