std::cout.precision() 메소드를 이용한다.precision()의 Argument(인자)로 출력할 유효숫자를 int형으로 넣어준다.#include <iostream>
int main() {
const double PI = 3.1415926535;
// 1. 일반 출력
std::cout << PI << std::endl;
// 2. 소수점 자릿수 조절 1 (유효숫자)
std::cout.precision(3);
std::cout << PI << std::endl;
// 3. 소수점 자릿수 조절 2 (소수점 아래)
std::cout << std::fixed; // fixed를 쓰면 소수점 아래 개수
std::cout.precision(3);
std::cout << PI << std::endl;
// 4. 고정 후 다른 수 출력
const double Num = 10.30293737;
std::cout << Num << std::endl;
// 5. 소수점 자릿수 조절 3 (소수점 아래)
std::cout.setf(std::ios_base::fixed);
std::cout.precision(6);
std::cout << PI << std::endl;
// 6. 소수점 자릿수 고정 해제
std::cout.unsetf(std::ios_base::fixed);
std::cout << PI << std::endl;
}
🖥️ 출력
1 3.14159
2 3.14
3 3.142
4 10.303
5 3.141593
6 3.14159
std::cout.precision(3)으로 설정할 경우 유효숫자가 3개까지만 출력된다. (std::fixed는 소수점 아래를 고정시킴)std::fixed를 사용하면 소수점 아래 유효숫자 개수로 자릿수를 정할 수 있다.std::fixed는 std::cout.setf로도 설정할 수 있다. (ios_base 클래스의 멤버 함수인 fixed를 이용하여 출력형식지정자를 설정)std::cout.unsetf를 이용하여 소수점 자릿수 고정을 해제할 수 있다.출처
'[C++]소수점 자릿수 정하기', https://wn42.tistory.com/82, (2022. 12. 15.)