Kotlin String Literal Format 2 Decimal Point

December 28, 2018
val name = "PI"
val value = 3.14159265358979323

// PI=3.14
val output = "$name=%.2f".format(value)

or

fun Double.formatDecimal(digits: Int) = "%.${digits}f".format(this)

// PI=3.14
val output = "$name=${value.formatDecimal(2)}"
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.