Kotlin String format() method example

Posted on Jan 03, 2022

Learn how to use Kotlin String.format() method to format your string values

Kotlin borrows the String.format() method from the Java language, so you can format your string values with it.

For example, suppose you want to format the PI value into a two-digit format (3.14)

Here’s how you can format the digits:

val PI = 3.14159265358979323
val myStr = String.format("The PI value is %.2f", PI)

print(myStr)// The PI value is 3.14

Like in Java, the first argument of the format() function will be the string format, while the rest would be the values to put into the string.

The %f inside the string is used to format a floating value. The .2 is added to limit the floating-point to 2 digits.

If you want to pass a String value to the format, you can use the %s specifier as follows:

val name = "Nathan"
val myStr = String.format("My name is %s", name)

print(myStr)// My name is Nathan

Here’s a full list of specifiers you can use in Kotlin:

  • %b - Boolean
  • %c - Character
  • %d - Signed Integer
  • %e - Float in Scientific Notation
  • %f - Float in Decimal Format
  • %g - Float in Decimal or Scientific Notation, depending on the value
  • %h - Hashcode of the supplied argument
  • %n - Newline separator
  • %o - Octal Integer (base 8)
  • %s - String
  • %t - Date or Time
  • %x - Hexadecimal Integer (base 16)

You can use as many specifiers as you need in your String.format() method.

Here’s an example of using 3 specifiers in the string format (a Boolean, a String, and an Integer):

val myStr = String.format("%b | %s | %d", false, "Morning", 90)

print(myStr)// false | Morning | 90

Kotlin will run the formatter from left to right, taking the second argument as the first value for the string format and so on.

And that’s how you can format string values using Kotlin String.format() method 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.