我正在开发一个C ++程序,其中包含许多类型为double的数字(数百万和数十亿的值,小数点右边只有几个位置)。我正在对这些数字执行计算,然后将结果打印到text / CSV文件。我注意到在文本文件中,我的所有数字都显示为四舍五入(六位数)。因此,在我的输出文件中,值13,169,911显示为13,169,900。
这种四舍五入仅在印刷品上出现吗?为了获得变量中的完整位数,我只需要在写入文件时指定一些内容吗?我在下面的文件代码中包含了一个示例:
void PrintPropFinance(vector<PropFinance>& PF, int NumProps, int Iterations, int ForecastLength,
string CurDeal, string ModelRunID, string ScenName, Assumptions& Ass) {
string filename;
ofstream OutFile;
ostringstream s1;
s1 << BASEPATH << "Output/" << CurDeal << "_" << ModelRunID << "_" <<
ScenName << "_PropFinance" << ".csv";
filename = s1.str();
OutFile.open(filename);
// Put in the column headers first
OutFile << "PropID" << ","
<< "Item" << ","
<< "StartDate" << ","
<< "NumOfPeriod" << ","
<< "Result" << ","
<< "Isap" << ","
<< "CurLoanBal" << ","
for (int i=1; i<=NumProps; ++i) {
// Populate the single-vector variables
OutFile << PF[i].PropID << ","
<< PF[i].Item << ","
<< PF[i].StartDate << ","
<< PF[i].NumOfPeriod << ","
<< PF[i].Result << ","
<< PF[i].Isap << ","
<< PF[i].CurLoanBal << ","
<< endl;
}
OutFile.close();
}
// Prop finance class definition
class PropFinance {
public:
string PropID;
int Item;
string StartDate;
int NumOfPeriod;
string Isap;
double CurLoanBal;
}
答案 0 :(得分:4)
问题可能与输出流产生double
的输出的方式有关:如果13169911
以“科学记数法”打印,它看起来像1.31699E7
。 Excel会很好地读取这种表示法,但会为它没有“看到”的数字加零,使得数字看起来像13,169,900
。
要解决此问题,请在输出double
时添加fixed
操纵器以确保打印所有数字:
OutFile << PF[i].PropID << ","
<< PF[i].Item << ","
<< PF[i].StartDate << ","
<< PF[i].NumOfPeriod << ","
<< fixed << PF[i].Result << ","
<< PF[i].Isap << ","
<< fixed << PF[i].CurLoanBal << ","
<< endl;
答案 1 :(得分:3)
您需要使用std::setprecision
来提高流的精度。默认情况下,iostream
只有6位精度。
试试这个:
OutFile << std::setprecision(std::numeric_limits<long double>::digits10 << PF[i].CurLoanBal;
请记住,这会影响流上的所有后续操作。说实话,这可能就是你想要的!
作为std::setprecision
和std::fixed
之间的比较,此程序:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>
int main()
{
const long double test_value = 13169911.7777777;
std::cout << "default precision (6): " << test_value << '\n'
<< "std::fixed: " << std::fixed << test_value << '\n'
<< "std::precision(10): " << std::defaultfloat << std::setprecision(10) << test_value << '\n'
<< "std::precision(10) & std::fixed: " << std::fixed << std::setprecision(10) << test_value << '\n'
<< "max precision: " << std::defaultfloat << std::setprecision(std::numeric_limits<long double>::digits10) << test_value << '\n'
<< "max precision & std::fixed: " << std::fixed << std::setprecision(std::numeric_limits<long double>::digits10) << test_value << '\n'
;
}
生成此输出:
default precision (6): 1.31699e+007
std::fixed: 13169911.777778
std::precision(10): 13169911.78
std::precision(10) & std::fixed: 13169911.7777777000
max precision: 13169911.7777777
max precision & std::fixed: 13169911.777777700000000
所以我认为您可能需要std::setprecision
而不是std::fixed
。虽然我想你无论如何都只有两位小数,所以也许没关系。
在此处阅读更多内容:http://en.cppreference.com/w/cpp/io/manip/setprecision