Today
Yesterday
Total
  • 💡 [Kotlin] Double형 변수 소수점 자릿수 설정, 반올림, 올림, 내림
    | 프로그래밍 분야/Kotlin 2021. 7. 26. 21:15

    코틀린에서 Double형 변수를 표현하는 방법은 여러가지가 있습니다.

     

    그 중 가장 강력한 것으로 String.format() 메서드를 먼저 보겠습니다.

     

    String.format()

    kotlin
    닫기
    fun main() { val dNum:Double = 454.14600 ‌println(String.format("%.0f", dNum/100).toDouble() * 100) // 500.0 ‌println(String.format("%.2f", dNum)) // 454.15 ‌println(String.format("%.8f", dNum)) // 454.14600000 }

     

    이렇듯 String.format() 메서드를 사용하여 C언어에서 float타입 변수를 format 표현식으로 자유롭게 가공했던 방법을 그대로 사용할 수 있습니다. 소숫점의 자릿수를 정할수도, 반올림할 자릿수를 정할수도 있습니다.

     

    String.format() 메서드의 리턴타입은 String입니다. (숫자로 이루어진 문자열)

     

     

    kotlin.math.round()

    kotlin
    닫기
    import kotlin.math.round fun main() { val dNum:Double = 454.14600 ‌println(round(dNum)) // 454.0 ‌println(round(dNum*100) / 100) // 454.15 }

     

    kotlin 표준 라이브러리인 kotlin.math의 round()함수를 이용하여 소수점 아래 부분을 반올림해서 ~~~.0 으로 나타낼 수 있습니다. 위와 같이 변수를 가공하여 반올림할 위치를 정할 수도 있습니다.

     

    String.format()과 같이 소수점의 위치를 지정할수는 없습니다.

     

     

    roundToInt(), roundToLong()

    kotlin
    닫기
    import kotlin.math.roundToInt import kotlin.math.roundToLong fun main() { val dNum:Double = 454.14600 ‌println(dNum.roundToInt()) // 455 ‌println(dNum.roundToLong()) // 455 }

     

    roundToInt()와 roundToLong() 메서드 또한 위의 kotlin.math.round()함수와 동일하게 동작합니다. Double 클래스에 메서드가 선언되어있어 체인 메서드 방식으로 간결하게 작성할 수 있습니다.

     

    다만, roundToLong() 메서드의 반환타입은 Int가 아닌 Long입니다.

     

     

    올림, 내림 - kotlin.math.ceil(), kotlin.math.floor()

    kotlin
    닫기
    import kotlin.math.ceil import kotlin.math.floor fun main() { val dNum:Double = 454.14600 ‌println(ceil(dNum)) // 455.0 ‌println(floor(dNum)) // 454.0 }

     

    ceil과 floor, 천장과 마룻바닥이라는 뜻입니다.

    수학에서는 올림과 버림을 의미하며, 소수점 이하 숫자들을 올림하거나 버림합니다.

sangilyoon.dev@gmail.com