开发者

Formatting string in Java using return string.format(...)

开发者 https://www.devze.com 2023-04-01 05:24 出处:网络
Say I want to return something like this: \"Title bookTitle, Author bookAuthor: $cost\" The ones in bold are variables.

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(开发者_如何学Go"%s .., blah blah")


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);


2 strings and a float with precision 2

String.format("Title %s, Author %s: $%f.2", bookTitle, bookAuthor, cost);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消