2011-06-30 11 views
2

私はこの質問は、私が文字列にダブルキャスティングに関する以前の質問へのフォローアップだと思います。ラウンドダブルと文字列にキャスト

私には、数字を表す文字列が与えられたAPIがあります。この数値を精度の小数点以下2桁に丸めて文字列として返す必要があります。私の試みは次のとおりです:

void formatPercentCommon(std::string& percent, const std::string& value, Config& config) 
{ 
    double number = boost::lexical_cast<double>(value); 
    if (config.total == 0) 
    { 
     std::ostringstream err; 
     err << "Cannot calculate percent from zero total."; 
     throw std::runtime_error(err.str()); 
    } 
    number = (number/config.total)*100; 
    // Format the string to only return 2 decimals of precision 
    number = floor(number*100 + .5)/100; 
    percent = boost::lexical_cast<std::string>(number); 

    return; 
} 

残念ながら、キャストは「丸められていない」値をキャプチャします。 (つまり、数値= 30.63、パーセント= 30.629999999999)誰もが自然に何を望むかを得るために、ダブルを丸めて文字列にキャストするクリーンな方法を提案する人はいますか?

ご協力いただきありがとうございます。 :)

答えて

6

ストリームは、C++の通常の書式設定機能です。この場合、にstringstreamは、トリックを行います:

std::ostringstream ss; 
ss << std::fixed << std::setprecision(2) << number; 
percent = ss.str(); 

あなたはおそらくすでにあなたの前のポストからsetprecisionに精通しています。 fixed ここでは、精度が整数全体の有効桁数を設定する代わりに、小数点以下の桁数に影響を与えるために使用されています。

+0

多くの感謝!私は本当にsnprintf()を使って一時的な文字配列とフォーマットを作ることに頼る必要はありませんでした。 :) – Rico

3

私はこれをテストしていませんが、私は次のように動作するはずと信じています:

string RoundedCast(double toCast, unsigned precision = 2u) { 
    ostringstream result; 
    result << setprecision(precision) << toCast; 
    return result.str(); 
} 

これが変換を行っているostringstreamの精度を変更するsetprecisionマニピュレータを使用しています。

0

ここには、ホイールを再発明せずに、必要なものすべてを実行するバージョンがあります。

void formatPercentCommon(std::string& percent, const std::string& value, Config& config) 
{ 
    std::stringstream fmt(value); 
    double temp; 
    fmt >> temp; 
    temp = (temp/config.total)*100; 
    fmt.str(""); 
    fmt.seekp(0); 
    fmt.seekg(0); 
    fmt.precision(2); 
    fmt << std::fixed << temp; 
    percent = fmt.str(); 
} 
関連する問題