2017-08-25 101 views
-4

我有一个包含秒数的可能是负数的double,我想要一个格式为H:mm:ss.hhh的字符串或-H:MM:ss.hhh将秒转换为小时,分钟,seconds.hundreths第二秒

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(); 
} 
+0

首先,你需要在函数内部创建一个空白字符串。然后我会参考这个页面来添加int到字符串。 https://stackoverflow.com/questions/45505477/append-int-to-stdstring阅读后,它只是做所有的单位转换,并将它们与适当的标点符号一起附加。 – 2017-08-25 15:48:48

回答

1

让我知道这是否适合你。我敢打赌有一个更简单的方法。

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(); 
} 
+1

或多或少。我将发布工作解决方案作为答案,但它几乎遵循这种模式。 – JCx

1

下面是使用升压解决方案。 假设你有boost::uint64_t secondsSinceEpoch代表自纪元以来的秒数(我个人并没有在这种情况下使用double的想法,对不起)。 然后得到一个字符串表示只是使用boost::posix_time::to_simple_string(secondsSinceEpoch);

+0

它实际上很接近。我现在没有提升为依赖,否则这可能是一个很好的解决方案。秒是双打,因为我们正在处理几分之一秒。 – JCx

+0

虽然在类似的脉络..也许这是我可以用strftime做... – JCx

+1

处理时间是一个和平的蛋糕升压:: posix_time :: ptime。不要重新发明轮子 – Dmitry

0
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(); 
} 

这是非常正确的。实际的实现使用缓存来避免在屏幕重新呈现时重新进行所有操作。

相关问题