How do I round a double to certain decimals in KMM...
# multiplatform
j
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
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
Will there be issues with double calculation inaccuracy? For example, I don't want 2.64.fractionDigits(1) to be like 2.60000000000001