2012-10-17 30 views
-5

我有一個數字100000.我需要顯示像100,000。如何在不使用的情況下使用Java中的字符串操作函數來實現此。提前致謝。數字格式或Java

+1

我敢肯定,你將不得不使用一個字符串處理函數。你爲什麼不想?而JavaScript/jQuery與Java非常不同。 – Ian

+0

如果我們有Jquery或Javascript。我可以在前端控制它。如果我們有java,我可以在後端使用它。 –

+1

好的,但爲什麼你不想使用字符串操作函數,爲什麼這很重要? – Ian

回答

1

使用NumberFormat執行或在Java中DecimalFormat類可用。

例如

DecimalFormat dFormat = new DecimalFormat("#,##,####"); 
String value = dFormat.format(100000); 
System.out.println("Formatted Value="+value); 
0

快速谷歌,我從here得到這個。

此功能未嵌入到JavaScript中,因此需要使用自定義代碼。以下是向數字中添加逗號並返回字符串的一種方法。

function addCommas(nStr) 
{ 
    nStr += ''; 
    x = nStr.split('.'); 
    x1 = x[0]; 
    x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
     x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    return x1 + x2; 
} 
0

做到這一點最簡單的方法是:

function addCommas(num) {return (""+num).replace(/\B(?=(?:\d{3})+(?!\d))/g,',');} 

更完整的版本,其中包括任意精度的十進制數的支持,請numbar_format on PHPJS

0

以下是一個Java的解決方案只使用字符串方法查找長度和字符位置,如果您仍然感興趣。

int counter = 0; 
    int number=123456789; 
    String str = Integer.toString(number); 
    String finalStr = new String(); 

    for(int i = str.length()-1; i >= 0; i--){ 
     counter++; 
     if(counter % 3 == 0 && i != 0){ 
      finalStr = ","+str.charAt(i)+finalStr; 
     } 
     else{ 
      finalStr = str.charAt(i)+finalStr; 
     } 
    } 

    System.out.println("Final String: "+finalStr); 

它使用值的長度向下循環並從右向左構建新字符串。在每個第三個值(除了最後一個值)之後,它將在字符串前添加一個逗號。否則,它將繼續並在逗號之間的臨時值中構建字符串。

所以這將打印到控制檯:

最終的字符串:123,456,789