2011-06-30 219 views
2

我想這個問題是我之前關於將一個double轉換爲一個字符串的問題的後續。Round Double並轉換爲字符串

我有一個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++中通常的格式化工具。在這種情況下,一個字符串流會做的伎倆:

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

你可能已經從以前的帖子熟悉setprecisionfixed 此處用於使精度影響小數點後的位數,而不是設置整數的有效位數。

+0

非常感謝!我真的不想不得不使用snprintf()創建一個臨時字符數組和格式。 :) – Rico

3

我沒有測試過這一點,但我認爲有以下應該工作:

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

它使用setprecision操縱更改是做轉換ostringstream的精度。

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(); 
} 
相關問題