String.format()格式化Java中的double


177

我如何使用String.format(format String,X)格式化如下所示的double?

2354548.235-> 2,354,548.23

谢谢!

Answers:


295
String.format("%1$,.2f", myDouble);

String.format 自动使用默认语言环境。


36
您也可以使用String.format(Locale.GERMAN, "%1$,.2f", myDouble);
OlivierGrégoire'02

13
如果要格式化的双精度字不止一个,请使用%1,%2等。例如String.format(“%1 $ ,. 2f,%2 $ ,. 2f”,myDouble,aDouble)
Moesio 2013年

4
我相信在这种情况下,“%1 $”是可选的。对我来说仅使用“%,. 2f”作为String格式。
Matt Passell 2014年

5
是的,马特是对的。%1, %2等等可以用来根据输入参数的索引对输出进行重新排序。看到这个。您可以省略索引,格式化程序将采用默认顺序。
praneetloke '16

1
您应该解释一下不同部分的含义。
MitulátBATI
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.