String formatting in Kotlin: how to output floating-point numbers and percentages?
Hi everyone! I just started learning Kotlin and encountered a problem with string formatting. In Java, I'm used to using `String.format("%.2f", value)` or `System.out.printf()`, but in Kotlin it doesn't work as I expected.
Here's an example. I'm writing a simple calculator for calculating a discount. I have a product price and a discount percentage, and I want to output the final amount with two decimal places and the percentage itself as "15%".
```kotlin
fun main() {
val price = 1250.0
val discount = 15
val finalPrice = price * (100 - discount) / 100
// Trying to output as in Java
println(String.format("Price with discount: %.2f", finalPrice))
println(String.format("Discount: %d%%", discount))
}
```
It seems to work, but I've heard that Kotlin has more idiomatic ways. Besides t
No answers yet.
Log in to leave an answer
Blogs