2014-01-19 14 views
-1

我想将我的最终双精度值 (即(1.0) )打印出来,例如$ 1.00。这在Java中如何实现?Java中的十进制和特殊格式

我导入了java.lang。* DecimalFormat formatter = new DecimalFormat(“#。00”);

不知道如何获得美元符号。我不知道是否有任何其他方式出国出境“$”这样做一边+ .....

+1

你可以显示你的代码(你有什么试过)? – Raptor

回答

0

使用String.format

// Format double with 2 decimal places and add a dollar sign 
String price = "$" + String.format("%.2f", myDouble); 

要直接打印,使用PrintWriter.printf,例如在System.out

System.out.printf("$%.2f", myDouble); 
+1

老实说,printf或NumberFormat是一个更直接的解决方案,忽略这个问题是一个dup。 –

+0

@BrianRoach是的,首先考虑使用'printf',但将其改为'String.format',因为它允许使用该值而不是仅仅打印它。而且,你可以使用'NumberFormat',但我个人更喜欢简单。感谢您的反馈:) –

0

使用DecimalFormat

double value = 1.0; 
    DecimalFormat dformat = new DecimalFormat("#.00"); 
    String modifiedVal = dformat.format(value); 
    System.out.println("$"+modifiedVal); 
+1

老实说,printf或NumberFormat是一个更直接的解决方案,忽略这个问题是一个dup。 –

+0

@BrianRoach:谢谢,过来认识一件新事物.. :) – gowtham

0

NumberFormat类有货币格式预先定义的实例。

double value = 1.0; 
NumberFormat nf = NumberFormat.getCurrencyInstance(); 
System.out.println(nf.format(value)); 
0

您可以在Java中使用的Locale & NumberFormat类。

NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en","US")); 
System.out.println(formatter.format(1.0));