kotlin 少数以下の切り下げを行う

kotlin 少数以下の切り下げを行う

kotlinで、少数以下の切り下げを行う手順を記述してます。「Math.floor」に対象の数値を指定します。

環境

  • OS windows11 home
  • java 19.0.1
  • kotlin 1.7.20-release-201

手順

少数以下の切り下げを行うには、「Math.floor」で可能です。

Math.floor( 数値 )

実際に、使用してみます。

fun main() {

    var num = 1.4567

    println( Math.floor(num) ) // 1.0

    num = 1.5678

    println( Math.floor(num) ) // 1.0

    num = -1.5678

    println( Math.floor(num) ) // -2.0

}

切り下げされていることが確認できます。マイナスは、負の方に丸められます。

「truncate」を使用すると「0」の方に丸められます。

import kotlin.math.*  

fun main() {

    println( truncate(1.9) ) // 1.0
    println( truncate(-1.9) ) // -1.0

}

桁数指定

桁数指定する場合は、以下のように一度演算してから「Math.floor」を実行します。

fun main() {

    var num = 1.23456

    println( Math.floor(num * 10.0) / 10.0 )       // 1.3
    println( Math.floor(num * 100.0) / 100.0 )     // 1.24
    println( Math.floor(num * 1000.0) / 1000.0 )   // 1.235

}