String.format()在java中格式化double

kik*_*ike 169 java

我如何使用String.format(格式字符串,X)来格式化双如下?

2354548.235 - > 2,354,548.23

谢谢!

Dav*_*ang 285

String.format("%1$,.2f", myDouble);
Run Code Online (Sandbox Code Playgroud)

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

  • 您还可以使用`String.format(Locale.GERMAN,"%1 $,.2f",myDouble)来使用特定的语言环境. (34认同)
  • 如果要格式化多个double,请使用%1,%2,依此类推.例如String.format("%1 $,.2f,%2 $,.2f",myDouble,aDouble) (13认同)
  • 是的,马特是对的.`%1,%2`等可用于根据输入参数的索引重新排序输出.见[this](https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html).您可以省略索引,格式化程序将采用默认顺序. (3认同)
  • 您应该解释不同部分的含义。 (3认同)
  • 我认为"%1 $"在这种情况下是可选的.仅使用"%,.2f"作为格式字符串为我工作. (2认同)

小智 39

String.format("%4.3f" , x) ;
Run Code Online (Sandbox Code Playgroud)

这意味着我们在ans中需要总共4位数,其中3位应该在十进制之后.f是double的格式说明符.x表示我们想要找到它的变量.为我工作...


mdr*_*drg 24

如果要使用手动设置的符号对其进行格式化,请使用:

DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
decimalFormatSymbols.setDecimalSeparator('.');
decimalFormatSymbols.setGroupingSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00", decimalFormatSymbols);
System.out.println(decimalFormat.format(1237516.2548)); //1,237,516.25
Run Code Online (Sandbox Code Playgroud)

但是,基于区域设置的格式是首选.

  • 有用的答案!但是,最后一句"基于区域设置的格式是首选,但"没有上下文就没有意义.当您想要生成特定格式的String时,有很好的用例,您不应该使用基于区域的格式.例如,您正在实现将数据导出到外部文件,并且您希望完全控制格式,而不依赖于当前(或任何)区域设置. (3认同)

Gur*_*oca 18

从此链接提取的代码;

Double amount = new Double(345987.246);
NumberFormat numberFormatter;
String amountOut;

numberFormatter = NumberFormat.getNumberInstance(currentLocale);
amountOut = numberFormatter.format(amount);
System.out.println(amountOut + " " + 
                   currentLocale.toString());
Run Code Online (Sandbox Code Playgroud)

此示例的输出显示了相同数字的格式如何随Locale而变化:

345 987,246  fr_FR
345.987,246  de_DE
345,987.246  en_US
Run Code Online (Sandbox Code Playgroud)


Tor*_*res 13

public class MainClass {
   public static void main(String args[]) {
    System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);

    System.out.printf("Default floating-point format: %f\n", 1234567.123);
    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
    System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
    System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);

    System.out.printf("Line-up positive and negative values:\n");
    System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
  }
}
Run Code Online (Sandbox Code Playgroud)

打印出来:

3(3)+3 00003
默认浮点格式:1234567,123000
带逗号的
浮点:1.234.567,123000 负浮点默认值:-1.234.567,123000
负浮点选项:(1.234.567, 123000)


排列正负值:1.234.567,12
-1.234.567,12