Java: utilizzare la classe Formatter. Esempi di utilizzo atteso:
StringBuilder sb = new StringBuilder();
// Send all output to the Appendable object sb
Formatter formatter = new Formatter(sb, Locale.US);
// Explicit argument indices may be used to re-order output.
formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
// -> " d c b a"
// Optional locale as the first argument can be used to get
// locale-specific formatting of numbers. The precision and width can be
// given to round and align the value.
formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
// -> "e = +2,7183"
// The '(' numeric flag may be used to format negative numbers with
// parentheses rather than a minus sign. Group separators are
// automatically inserted.
formatter.format("Amount gained or lost since last statement: $ %(,.2f",
balanceDelta);
// -> "Amount gained or lost since last statement: $ (6,217.58)"
fonte
2010-07-09 11:56:26
Si prega di non contrassegnare una 'printf'-domanda' 'C++. –
@ Space_C0wb0y: Non c'è niente di sbagliato nell'usare printf in C++. In un mondo ideale tutti userebbero iostream nel loro C++, ma non viviamo in un mondo ideale. Inoltre, a volte è più semplice ottenere una stringa formattata nel modo desiderato con printf. – George
A mio parere c'è davvero molto sbagliato nell'usare 'printf' in C++. C e C++ sono due linguaggi completamente diversi, e le persone fanno supposizioni diverse su quali caratteristiche C sono OK in C++ e quali no. Le diverse ipotesi portano sempre a problemi. –