2012-11-28 22 views
2

可能重複:
Does setprecision in c++ round? If so why am I seeing this?問題而四捨五入用C十進制的Fileds ++使用setprecision

這裏是我使用

char* round(double value, int decimal_places) 
{ 
decimal_places = decimal_places+1; 
std::stringstream s2; 
    s2 << std::setprecision(decimal_places) << std::setiosflags(std::ios_base::fixed) << value; 
std::string st = s2.str(); 
    return st; 
} 

我的輸入值的函數0.89425並且小數宮殿的數量是4

我的輸出是0.8942,但我想要0.8943,即如果在我所需的小數位後面的下一個數字大於等於5,那麼輸出應舍入到下一個值。

回答

1

0.89425不能準確表示二進制浮點;最接近的可表示值爲0.894249999999999989341858963598497211933135986328125,正確舍入到十進制數0.8942。

如果要查看小數四捨五入行爲,請使用定點或十進制浮點數。