主题:等考二级C++:浮点数的格式化
http://www.educity.cn
string do_fraction(long double value, int decplaces=3)
char DECIMAL_POINT='.';
int prec = numeric_limits<long double>::digits10; // 18
out.precision(prec);//override default
out << value;
string str= out.str(); //extract string from stream
size_t n=str.find(DECIMAL_POINT);
if ((n!=string::npos) //is there a decimal point?
&& (str.size()> n+decplaces)) //is it followed by at
//least decplaces digits?
{
str[n+decplaces]='';//overwrite first redundant digit
}
str.swap(string(str.c_str()));//get rid of spurious
//characters after the nul
return str;
}
如
cout << do_fraction(123456789.69999001) << endl;
cout << do_fraction(12.011) << endl;
输出
123456789.69
12.01
string do_fraction(long double value, int decplaces=3)
char DECIMAL_POINT='.';
int prec = numeric_limits<long double>::digits10; // 18
out.precision(prec);//override default
out << value;
string str= out.str(); //extract string from stream
size_t n=str.find(DECIMAL_POINT);
if ((n!=string::npos) //is there a decimal point?
&& (str.size()> n+decplaces)) //is it followed by at
//least decplaces digits?
{
str[n+decplaces]='';//overwrite first redundant digit
}
str.swap(string(str.c_str()));//get rid of spurious
//characters after the nul
return str;
}
如
cout << do_fraction(123456789.69999001) << endl;
cout << do_fraction(12.011) << endl;
输出
123456789.69
12.01