2017-04-19 44 views
0

是否有設置數字小數的直接函數。例如我得到3.14341 和我的參數是2,所以我得到3.14。有一個功能setprecision但它只打印結果。此外,我做了這樣一個算法:根據參數設置十進制數

std::string fixPrecision(std::string const& value, int digits) 
{ 
    std::string num = value; 
    float temp = std::stof(num); 
    float fractpart, intpart; 
    fractpart = modf(temp, &intpart); 
    int a = (int)(fractpart * pow(10,digits)); 
    double last = intpart + a*(pow(0.1 , digits)); 
    return std::to_string(last); 
} 

它運作良好。我得到我想要的,但我必須將其轉換爲字符串,所以結果是123.120000而不是123.12

我可以確定在這裏使用一些幫助。提前致謝。

編輯:這不是一個重複的問題,因爲我的功能需要採取整數和字符串格式返回數字。再次感謝。

+0

你爲什麼要在內部舍入數字。通常情況下,只有在顯示時才需要將其舍入。通常不需要擺脫精度。如果您正在使用貨幣類型,那麼您應該使用整數/固定精度庫。 – NathanOliver

+0

這是我在公司的任務,數字應該用字符串發送,謝謝你的回答。 –

+0

這可以通過'std :: stringstream'和操縱符來實現,比如'std :: fixed'和'std :: setprecision'。但是,您可能需要考慮直接操縱字符串。使用中間「浮動」可能會損害您的精確度。 –

回答

0

我的傻瓜。答案就像這樣簡單。我做了很多不必要的事情...

std::string fixPrecision(std::string const& value, int digits) 
{ 
    auto pos = value.find("."); 
    if(pos != std::string::npos) 
    return value.substr(0, pos+digits+1); 
    return value; 
} 
0

不完全,但您可以設置使用的std :: setprecision精度

定義一個方法:

void printWithPrecision(const double value, unsigned decimalPlaces) 
{ 
    std::cout << "A Double with " << decimalPlaces <<" decimal places: "<<std::setprecision(decimalPlaces) << value << std::endl; 
} 

,並調用它像:

double d = 7987.12354689765416; 

for (auto x = 0; x<10; x++) 
{ 
    printWithPrecision(d, x); 
} 

不要忘記包括輸入輸出操縱器:

#include <iomanip> 
+0

謝謝你的答案,但我不想打印它,而不是我想分配它。 –

+0

但是這是一個雙重的,你只是不能修改定義它的53位(見:https://en.wikipedia.org/wiki/IEEE_754-2008) –

+0

可能是有一個字符串函數(後我轉換爲字符串) 爲了這... –