2017-08-25 18 views
-4

私は負数である可能性がある秒数を含む倍精度を持っています.H:mm:ss.hhhの形式の文字列が必要ですまたは-H:mm:ss.hhh秒を時、分、秒に変換します。秒の秒数を返します。

std::string getFormattedTime(double seconds) 
{ 
// magic voodoo 
} 

時間がゼロの場合は省略する必要があります。私は、さまざまな丸めと精度の問題で二回それをbuggeredアップしましたので、私は助けを求めるための時間だった考え出し:)

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それを読んだら、単なるすべての単位変換を行い、適切な句読点と一緒にそれらを追加するだけです。 –

答えて

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

時間を扱うことはboost :: 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(); 
} 

これはかなり右です。実際の実装では、キャッシュを使用して、画面の再レンダリング時にすべての操作をすべてやり直すことを回避します。

関連する問題