2014-10-02 173 views
2

我有下面的代碼,如何向逗號中添加逗號?

Scanner cin = new Scanner(System.in); 

System.out.print("Part-1- Enter the amount inout ($ 1,567.00):"); 
String amountStr = cin.nextLine(); 

String amountStr2 = amountStr.replace("$" , ""); 
String amountStr3 = amountStr2.replace("," , ""); 
double amountDouble = Double.parseDouble(amountStr3); 

double quarters = (amountDouble/.25); 
double quarters2 = Math.floor(quarters); 

int quartersFinal = (int) quarters2; 

我想返回數字結果爲6,269的結果。現在,代碼返回6269.我將如何添加逗號?

+0

你試過什麼......? – Ali786 2014-10-02 05:14:31

+2

在API文檔中查找'DecimalFormat'。 – vanza 2014-10-02 05:15:05

+0

http://joda-money.sourceforge.net/userguide.html – Ali786 2014-10-02 05:16:15

回答

2

您可以使用DecimalFormat

Scanner cin = new Scanner(System.in); 
System.out.print("Part-1- Enter the amount inout ($ 1,567.00):"); 
String amountStr = cin.nextLine(); 
String amountStr2 = amountStr.replace("$" , ""); 
String amountStr3 = amountStr2.replace("," , ""); 
double amountDouble = Double.parseDouble(amountStr3); 
double quarters = (amountDouble/.25); 
double quarters2 = Math.floor(quarters); 
DecimalFormat df = new DecimalFormat("#,###"); 
System.out.println(df.format(quarters2)); 

輸出地說:

6,268 
0

詳細試試這個

DecimalFormat df = new DecimalFormat("#,###.##"); 
String amountStr2 = amountStr.replace("$" , ""); 
String amountStr3 = amountStr2.replace("," , ""); 
double amountDouble = Double.parseDouble(amountStr3); 
df.format(amountDouble); 
0

的String.format(...)的閱讀文檔。將來你會多次需要它。