Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n) function you'd need to define yourself as
fun Double.format(digits: Int) = "%.${digits}f".format(this)
This will work only in Kotlin/JVM.
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
Answer from Andrey Breslav on Stack OverflowUnfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:
"pi = ${pi.format(2)}"
the .format(n) function you'd need to define yourself as
fun Double.format(digits: Int) = "%.${digits}f".format(this)
This will work only in Kotlin/JVM.
There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format())
See Kotlin's documentation
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
Java String.format alternative in kotlin? - Kotlin Discussions
String formatting library for Kotlin (or Java) like in fmt/rust/python
Kotlin String.format - Support - Kotlin Discussions
๐ต Your email address is not a string.
Videos
I'm trying to find a string formatting library for Kotlin, or Java, that uses similar specifiers like it's used in C++, Python or Rust. What I mean by that is shown on these examples:
// C++
std::cout << fmt::format("Hello 0x{:08X}\n", 123);This will print Hello 0x0000007B.
# Python
print("Hello {:.3}".format(1.0153))This will print Hello 1.02.
I'd like this lib mostly for consistency with my current sources in other languages. Does anyone know if such library exists? (I've tried to find one, but without any luck)