koos808

[파이썬] python 반올림, 올림, 내림 다양한 코드 본문

Python

[파이썬] python 반올림, 올림, 내림 다양한 코드

koos808 2020. 10. 27. 14:27
728x90
반응형

반올림, 올림, 내림

    • 소수점을 n번째 까지만 표현하고 반올림을 하고싶을때, round 함수를 사용

    • default는 소수점 첫번째 자리에서 반올림해서 정수로 표현된다.

    • Ex)

      n = 7/15 -> n = 0.4666666666666667
      >>> round(n,2)
      0.47
      >>> round(n,4)
      0.4667
      >>> round(n)
      0
      >>> type(round(n))
      <class 'int'>
  • 물론 정수도 반올림 가능하다.

    • Ex)

      >>> round(12345,-1)
      12340
      >>> round(12345,-2)
      12300
  • math.ceil(i) : 올림, math.floor(i) : 내림, math.trunc(i) : 버림

    • Ex)

      >>> import math
      >>> math.ceil(12.2)
      13
      >>> math.ceil(12.6)
      13
      >>> math.floor(12.2)
      12
      >>> math.floor(12.6)
      12
      >>> math.trunc(12.2)
      12
      >>> math.trunc(12.6)
      12
  • Array : Numpy Code

    • np.round(data, 2) or np.around(data, 2)
  • List 예제

    • Ex) list 내 값들 전체 반올림 하기
    - 기본 함수인 round()를 사용하면 안되고, np.round(list_name, 5)를 사용해주면 된다.
    
    - 이후 다시 리스트로 변환하고 싶으면 `list(np.round(list_name,5))` 를 이용.

728x90
반응형
Comments