String formatting in Kotlin: how to use String.format and templates?
Hi everyone! I just started learning Kotlin after Java and ran into a problem with string formatting. In Java, I used to use `String.format("%s %d", str, num)` or `System.out.printf(...)`. But in Kotlin, I see that string templates with dollar signs are often used: `"Hello, $name"`. This is convenient for simple cases, but what about when you need to format a number with a specific number of decimal places or align text by width?
For example, I have this code:
```kotlin
val price = 123.4567
val name = "Coffee"
// I want to output: "Product: Coffee, Price: 123.46 rub."
```
I tried writing `"Product: $name, Price: $price rub."`, but I get `123.4567` without rounding. I tried using `String.format("%.2f", price)`, but IDEA underlines it as deprecated or suggests replacing it with
No answers yet.
Log in to leave an answer
Blogs
Monorepository with C#: Code Organization for Beginners
C++ for backend vs frontend: choosing your side of the force
Docker and PHP: Advanced Application Containerization
Instantiate and Present ViewController in Swift: Complete Guide with Answers to Common Questions