C++:
// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
#include <iostream>
using namespace std;
void test_precision(double d) {
const streamsize ss = cout.precision(); // get default precision
cout << "default precision is " << ss << endl;
cout << d << endl;
cout << setprecision(5) << d << endl;
cout << fixed;
cout << d << endl;
cout << setprecision(6) << d << endl;
cout << setprecision(7) << d << endl;
cout << setprecision(8) << d << endl;
cout.precision(1); // Different way to set precision
cout << d << endl;
cout << defaultfloat << setprecision(ss); // restore default precision
printf("c way: %.2f\t%.15f\n", d, d);
}
int main() {
double d = 12.123456789;
test_precision(d);
cout << endl; // print new line
d = 1.123456789;
test_precision(d);
cout << endl; // print new line
d = 0.5;
test_precision(d);
return 0;
}
上面代码的输出
default precision is 6
12.1235
12.123
12.12346
12.123457
12.1234568
12.12345679
12.1
c way: 12.12 12.123456789000000
default precision is 6
1.12346
1.1235
1.12346
1.123457
1.1234568
1.12345679
1.1
c way: 1.12 1.123456789000000
default precision is 6
0.5
0.5
0.50000
0.500000
0.5000000
0.50000000
0.5
c way: 0.50 0.500000000000000