Formatting string in Java using return string.format(...)
31,921
Solution 1
String title = "bookTitle";
String author = "bookAuthor";
double cost = 100;
String text = String.format("Title %s, Author %s: $%.2f", title, author, cost);
System.out.println(text); // prints "Title bookTitle, Author bookAuthor: $100.00"
// or System.out.pritnf("Title %s, Author %s: $%.2f", title, author, cost);
Solution 2
2 strings and a float with precision 2
String.format("Title %s, Author %s: $%f.2", bookTitle, bookAuthor, cost);
Solution 3
String fs;
fs = String.format("Title %t, Author %a: $%c", bookTitle, bookAuthor, cost);
System.out.println(fs);
http://download.oracle.com/javase/tutorial/java/data/strings.html
Author by
Janezcka
Updated on September 02, 2020Comments
-
Janezcka over 3 years
Say I want to return something like this: "Title bookTitle, Author bookAuthor: $cost"
The ones in bold are variables. I can't figure out how to return this using string.format("%s .., blah blah")