format() 자릿수 설정

Jun Heo·2022년 12월 31일
0

1. 정수

print("{:03} {:02}".format(12, 5))
# 012 05

print("{0:05} {1:01}".format(301, 71))
# 00301 71

원하는 자릿수 만큼 0을 채울 수 있다.

2. 실수

print("{:.2f} {:.3f}".format(1.256, 0.33))
# 1.26 0.330

print("{1:.4f} {0:.1f}".format(21.2678, 2))
# 2.0000 21.3

실수의 소수점 자릿수를 원하는 자릿수만큼 표현할 수 있다. 자릿수를 줄이는 경우 반올림한다.

3. 정수와 실수

print("{:07.3f}".format(3.12))
# 003.120

print("{:05.2f}".format(1.347))
# 01.35

실수의 자릿수를 0으로 채울 때 소수점과 소수점 아래 자릿수를 포함해 전체 자릿수를 채운다.

0개의 댓글