I would like to format a Float to a String with 1 ...
# stdlib
d
I would like to format a Float to a String with 1 decimal, but I can’t find the way. If I write this:
Copy code
val myString = "%.1f".format(myFloat)
it tells me that the function
format
doesn’t exist?
g
Is it mpp? There is no mpp format function in Kotlin, it available only on jvm
d
yes, in mpp
this is what I ended up doing:
Copy code
private fun oneDecimal(number : Float) : String {
    var str = number.toString()
    return str.substring(0,str.indexOf(".")+2)
}
r
That won't round properly, and it won't localize if that's a concern. Also, if the number is extreme enough to merit exponent syntax (e.g. 6.02e23), you'll get really wrong results.
g
I would recommend to use expect/actual for format function, also will be helpful in future. It still not perfect, different platform format implementations are not identical, bit probably should work for this case, just write test in common