Most idiomatic way to convert a Float value to a string without a decimal point in Kotlin
I'd like to convert a Float
value to a String
, but without a decimal point. For example, for the following code:
fun toDecimalString(value: Float): String {
// TODO
}
fun main() {
println("Result: ${toDecimalString(1.0f)}")
println("Result: ${toDecimalString(1.999999f)}")
println("Result: ${toDecimalString(20.5f)}")
}
I'd like the expected output to be:
1
1
20
By converting to an Int
before turning the input to a string, all decimal point values are dropped, e.g.:
fun toDecimalString(value: Float): String = "${value.toInt()}"
As @Tenfour04 said, the answer is to first convert to an integer, by using .toInt()
, which only leaves the digits left of the decimal point, and then convert to string using .toString()
.
.toInt().toString()