Let's imagine something like this:
var num: Float = 0.0f
num = 2.4 * 3.5 / 3.8
num
has several decimals, but I want only 2.
In JS I would use num.toFixed(2)
.
Other answers here suggest to use "%.2f".format(num)
or num.format(2)
. The latter needs a custom extension function:
fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)
However, any of these options leads to a compiler error of "unresolved reference". I don't think it is a question of imports because the compiler would suggest it.
Is there an easy way to do this?