2015-12-24 49 views
2

我在做与格式的财务数据计算如下:向下取整/截断双

<up to 5 digits>.<two digits> 

基本上,在我的节目,我遇到浮点错误。举例来说,如果我有:

11.09 - (11.09 * 0.005) = 11.03455 

我希望能够使用11.03455,而不是系统产生什么:11.0345499999999 ...

我比较我的程序与价值观产生值我在文本文件是字符串格式。我只需要两位精度的小数点,我可以向下取整。有没有一种方法可以将其降至11.03?

我在想,如果我把它变成一个字符串,并且只是逐个字符地分析它,那只会在'。'之后添加两个字符。字符。这是一个好的解决方案吗?任何更好的想法?

以下是我有:

string dataProcessor::createTwoDec(double price){ 
    string s = to_string(price); 
    string output = ""; 
    int dist = 0; 
    int num_wanted = 0; 

    bool pt_found = false; 
    for(int i = 0; i < s.length(); i++){ 
     if(s[i] == '.') 
      pt_found = true; 
     if(pt_found) 
      dist++; 
     if(dist > 3) 
      break; 
     output += s[i]; 
     num_wanted++; 

    } 
    return output.substr(0, num_wanted); 
} 
+1

也许'round(value * 100.0)/ 100.0;'? – ForguesR

+1

*我正在计算财务数据* - 我希望您了解浮点计算的不精确性,以及为什么'double'可能不适合表示货币值和计算。 – PaulMcKenzie

+0

@PaulMcKenzie是的。 – jonnyd42

回答

1

你可以用下面的公式四舍五入由n个位数(n是不是太大):

round(x*10^n)/10^n 
where n is number of decimal places required. 

在你的情况, n是5。因此,这将是

result = round(result*100000)/100000; 

参见How do you round off decimal places in C++?

+0

让我尝试一下并回复你。 – jonnyd42