1

Is there a brief way in Kotlin to build formatted strings with variables, similar to f-strings in Python? For example:

f'My cat is {weight:.1f} pounds.'

Which would yield:

My cat is 25.3 pounds.

Carmen DiMichele
  • 555
  • 4
  • 18

2 Answers2

1

The usual way to do this is with String.format().

It's also an extension method on String, so you can call it as follows:

"My cat is %.1f pounds.".format(weight)

For details, see this question; the docs for the format patterns are here. (Both are for the Java version, but it's the same in Kotlin.)

gidds
  • 16,558
  • 2
  • 19
  • 26
0

As there was no good and multiplatform tool, I wrote MP library that implements a traditional printf-like formatting. It is used in many projects, it is simple and works everywhere the same (.format worked on JVM only - at least at the time I wrote the library):

https://github.com/sergeych/mp_stools

sergeych
  • 791
  • 7
  • 11