ใน C++ ขนาดของตัวเลขจุดลอยตัว (floating point) จะมีขนาด 4 ไบต์ (float) หรือ 8 ไบต์ (double) ทำให้จัดเก็บตำแหน่งทศนิยมได้จำนวนจำกัด ตัวอย่างเช่น 1/3 = 0.333333... ต่อเนื่องไปเรื่อยๆ หากเก็บไว้ในตัวแปรแบบ floating point จะจัดเก็บเฉพาะหลักที่สำคัญ (significant digits) ค่าเริ่มต้นคือ 6 หลัก ดังนั้นปกติ floating point ใน C++ จะแสดงผลได้สูงสุด 6 ตำแหน่งทศนิยม
เราสามารถเปลี่ยนความแม่นยำได้โดยใช้ setprecision ซึ่งอยู่ในไฟล์หัวข้อ <iomanip> ให้ดูตัวอย่างด้านล่างเพื่อเข้าใจแนวคิด
โค้ดตัวอย่าง
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x = 2.3654789;
cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl;
cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl;
cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl;
}
ผลลัพธ์
Print up to 3 decimal places: 2.365 Print up to 2 decimal places: 2.37 Print up to 7 decimal places: 2.3654789