format
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
| Conversion | Accepts |
|---|---|
%s %S, %b %B, %h %H | any value |
%c %C | Char, or a code point as Byte, Short or Int |
%d %o %x %X | Byte, Short, Int, Long |
%e %E %f %g %G %a %A | Float, Double |
%%, %n | no 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
%nis always"\n", also on Windows.There are no date and time conversions (
%t), and noBigInteger,BigDecimalorFormattablearguments.%sand%huse the value's KotlintoStringandhashCode.JS and Wasm can lose the difference between
Int,FloatandDoublein avararg Any?. There the conversion decides:%xtreats a small number asInt, and%ftreats a number asDouble. Pass aLongwhen 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.%Sand 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
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.
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.