본문 바로가기

Python

[Python] 파이썬 자릿수 조절(소수점, 반올림)

반올림

반올림을 하고 싶을 때는, 파이썬 내장 함수 round()를 사용한다.
round(number, ndigits = None)
: number를 소수점 다음에 ndigits정밀도로 반올림한 값을 돌려줌. ndigits 기본값 = None
ndigits = None인 경우 입력에 가장 가까운 정수(int)로 돌려줌.
ndigits에 음수를 입력한 경우 |음수|자리에 해당하는 곳에서 반올림.

n = 1 / 3
print(n)
# 0.3333333333333333

round(n, 2)
print(round(n, 2))
# 0.33  

round(n, 4)
print(round(n, 4))
# 0.3333

type(round(n, 4))
print(type(round(n, 4)))
# <class 'float'>

round(n)
print(round(n))
# 0

round(n, ndigits = None)
print(round(n, ndigits = None))
# 0

type(round(n))
print(type(round(n)))
# <class 'int'>

round(123456, -1)
print(round(123456, -1))
# 123460
# -1인 경우 일의 자리에서 반올림

round(123456, -3)
print(round(123456, -3))
# 123000
# -3 인 경우 백의 자리에서 반올림

 

참고
https://dpdpwl.tistory.com/94