Skip to main content

How to format a string?

Posted by malenkov on January 26, 2009 at 6:00 AM PST

Sometimes users need to prepare their data for output. Java provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. However, the JavaFX language reference just briefly mentions this functionality.

JavaFX Script enables developers to embed expressions into the string using the curly braces. It is very useful because the language does not support the plus operand for string concatenation.

Java: String str = "prefix" + object + "postfix";
JavaFX: var str = "prefix{object}postfix";

If users need to format the object, they could use the String.format method in Java. JavaFX Script supports the same format specifiers, but there is another syntax: "{[format ]variable}".
For example, user needs to render only two digits after the point:

Java: String str = String.format("cost: %.2f $", number);
JavaFX: var str = "cost: {%.2f number} $";

The format specifiers for general, character, and numeric types have the following syntax: %[flags][width][.precision]conversion. The optional flags present a set of characters that modify the output format. The set of the valid flags depends on the conversion. The optional width is a non-negative decimal integer indicating the minimum number of characters to be written into the output. The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion. The required conversion is a character that indicates how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

The detailed information about the format specifiers is available here. Note that the format specifiers in JavaFX do not use the argument index, because these specifiers are already placed before the argument.

Related Topics >>