使用return string.format(…)在Java中格式化字符串

使用return string.format(…)在Java中格式化字符串,java,string,format,Java,String,Format,假设我想退回这样的东西: “书名书名,作者书名:$成本” 粗体的是变量。 我不知道如何使用string.format(“%s..,诸如此类”)返回此内容 2个字符串和精度为2的浮点 String.format("Title %s, Author %s: $%f.2", bookTitle, bookAuthor, cost); String title = "bookTitle"; String author = "bookAuthor"; double cost = 100; String

假设我想退回这样的东西: “书名书名,作者书名:$成本

粗体的是变量。 我不知道如何使用string.format(“%s..,诸如此类”)返回此内容


2个字符串和精度为2的浮点

String.format("Title %s, Author %s: $%f.2", bookTitle, bookAuthor, cost);
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);
String.format("Title %s, Author %s: $%f.2", bookTitle, bookAuthor, cost);