2017-08-25 102 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(); 
} 

這是非常正確的。實際的實現使用緩存來避免在屏幕重新呈現時重新進行所有操作。

相關問題