https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
j

John Huang

03/21/2023, 7:37 PM
How do I round a double to certain decimals in KMM? For example: 0.6234.round(0.001, Round.down) should give 0.623 0.6234.round(0.001, Round.up) should give 0.624 0.6234.round(0.001, Round.nearest) should give 0.623 Ideally, it can round to 10's, 100's etc 6234.round(10, Round.down) should be 6230 6234.round(10, Round.up) should be 6240 6234.round(10, Round.nearest) should be 6230
h

Håkon Pettersen

03/22/2023, 8:04 AM
We have created an extension-function for this:
Copy code
internal fun Double.fractionDigits(fractionDigits: Int): Double {
    val factor = 10.0.pow(fractionDigits)
    return round(factor * this) / factor
}
j

John Huang

03/22/2023, 11:57 PM
Will there be issues with double calculation inaccuracy? For example, I don't want 2.64.fractionDigits(1) to be like 2.60000000000001
10 Views