Hiii.... what is the easiest method in kotlin to r...
# android
k
Hiii.... what is the easiest method in kotlin to round a float value upto 2 decimals and for all locales (whether it uses decimal point or decimal comma) currently i am using this method but it throws NumberFormatException for locales that use decimal comma.
Copy code
fun Float.round(decimals: Int = 2): Float = "%.${decimals}f".format(this).toFloat()
e
not really Android-related, but…
Copy code
import kotlin.math.pow
import kotlin.math.round
fun Double.roundDecimal(digits: Int = 2): Double {
    val scale = 10.0.pow(digits)
    return round(this * scale) / scale
}
fun Float.roundDecimal(digits: Int = 2): Float {
    val scale = 10.0f.pow(digits)
    return round(this * scale) / scale
}
☝️ 1
k
Thanks @ephemient