Search code examples
kotlinkotlin-multiplatform

How can I round a number in Kotlin-multiplatform without using external libraries?


I have a KMP project, and I want to round the doubles into the needed number of decimals, without implementing this in each platform, using primitive types and standard library is preferable.


Solution

  • You can create an extension function and use strings with functional methods like this:

    import kotlin.math.pow
    
    fun Double.roundTo(dec: Int): Double {
        return toString().split('.').let {
            if (it.last().length <= dec) this
            else {
                val decimals = it.last().drop(it.last().length - dec)
                (it.first() + decimals).toDouble() / 10.0.pow(dec)
            }
        }
    }
    

    Thanks for the feedback in the comments, I found a better way:

    import kotlin.math.pow
    import kotlin.math.round
    
    fun Double.roundTo(dec: Int): Double {
        return round(this * 10.0.pow(dec)) / 10.0.pow(dec)
    }