format

fun String.format(vararg args: Any?): String

Formats args into this pattern, with Java's String.format syntax, on every target.

The output is the output of java.util.Formatter with Locale.ROOT: . as the decimal point, , for grouping, and never the device locale.

Example

import io.github.yuroyami.kitecore.text.format

"%.1f%%".format(82.75) // "82.8%"
"%-6s|%,d".format("total", 1234567) // "total |1,234,567"
"%2\$s: %1\$08X".format(255, "mask") // "mask: 000000FF"

Supported syntax

ConversionAccepts
%s %S, %b %B, %h %Hany value
%c %CChar, or a code point as Byte, Short or Int
%d %o %x %XByte, Short, Int, Long
%e %E %f %g %G %a %AFloat, Double
%%, %nno argument: a %, and a line feed

Flags, width, precision, argument indexes (%2$s) and "same argument again" (%<s) work as on the JVM. A null argument prints null, or false for %b.

Compared with the JVM String.format

  • %n is always "\n", also on Windows.

  • There are no date and time conversions (%t), and no BigInteger, BigDecimal or Formattable arguments.

  • %s and %h use the value's Kotlin toString and hashCode.

  • JS and Wasm can lose the difference between Int, Float and Double in a vararg Any?. There the conversion decides: %x treats a small number as Int, and %f treats a number as Double. Pass a Long when you need 64 bits.

Watch out

  • Import io.github.yuroyami.kitecore.text.format. Without the import, common code does not compile, and JVM code silently uses the JVM version, which follows the device locale.

  • %S and the other upper-case conversions use the Unicode data of the runtime. A very new character can differ between runtimes.

Receiver

the pattern, in java.util.Formatter syntax.

Parameters

args

the values for the conversions, in order.

Throws

if the pattern is invalid, an argument is missing, or an argument has the wrong type for its conversion.


fun String.Companion.format(format: String, vararg args: Any?): String

Formats args into the pattern format: the String.format(pattern, args) call shape.

String.format("%2\$s: %1\$08X", 255, "mask")   // "mask: 000000FF"

It gives the same output as format.format(*args). The syntax, the differences from the JVM and the import are on String.format.

Throws

if the pattern is invalid, an argument is missing, or an argument has the wrong type for its conversion.