2016-11-09 14 views
3

我想將這種格式應用於給定的int數#´###,###我嘗試使用DecimalFormat class,但它只允許有一個分組分隔符符號,當我需要爲成千上萬的數字和逗號分配兩個accute accent如何在java中格式化int數字?

所以最終我能以這種方式1´000,000

+0

檢查http://stackoverflow.com/questions/5114762/how-do-format-a-phone-number-as-a-string-in-java – Roshan

+0

@Roshan在這個問題的解決方案使用'substring ()'或者'replace()',這對手機的「數字」可能是正確的,但在處理實際數字時(例如金錢),這並不是最好的想法。 OP需要考慮負數,沒有小數點的數字等。 – walen

+0

謝謝@Roshan! –

回答

1

我發現鏈接@Roshan的意見提供了有用的,這個解決方案是使用正則表達式表達和replaceFirst方法

public static String audienceFormat(int number) { 
    String value = String.valueOf(number); 

    if (value.length() > 6) { 
      value = value.replaceFirst("(\\d{1,3})(\\d{3})(\\d{3})", "$1\u00B4$2,$3"); 
     } else if (value.length() >=5 && value.length() <= 6) { 
      value = value.replaceFirst("(\\d{2,3})(\\d{3})", "$1,$2"); 
     } else { 
      value = value.replaceFirst("(\\d{1})(\\d+)", "$1,$2"); 
     } 

    return value; 
} 

我不知道該解決方案具有性能影響,還我ROCKIE用正則表達式,所以這段代碼可能會被縮短。

-1

也許嘗試使用此格式像1,000值或數百萬,與你的空格或逗號之前想個位的「#」。

String num = "1000500000.574"; 
    String newnew = new DecimalFormat("#,###.##").format(Double.parseDouble(number)); 
+0

如果這工作只是讓我知道 –

+0

OP專門說,DecimalFormat不起作用。 – walen

+0

謝謝@TiagoFutre,但它的格式不適用於我的具體情況 –

1

我總是喜歡使用的String.format,但我不知道是否有將兩種格式一樣,數字的語言環境。這裏有一些代碼可以完成這項工作。

// Not sure if you wanted to start with a number or a string. Adjust accordingly 
String stringValue = "1000000"; 
float floatValue = Float.valueOf(stringValue); 

// Format the string to a known format 
String formattedValue = String.format(Locale.US, "%,.2f", floatValue); 

// Split the string on the separator 
String[] parts = formattedValue.split(","); 

// Put the parts back together with the special separators 
String specialFormattedString = ""; 
int partsRemaining = parts.length; 
for(int i=0;i<parts.length;i++) 
{ 
    specialFormattedString += parts[i]; 
    partsRemaining--; 
    if(partsRemaining > 1) 
     specialFormattedString += "`"; 
    else if(partsRemaining == 1) 
     specialFormattedString += ","; 
} 
1

試試這個,這些Locale格式在您所需的格式。

List<Locale> locales = Arrays.asList(new Locale("it", "CH"), new Locale("fr", "CH"), new Locale("de", "CH")); 
    for (Locale locale : locales) { 
     DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(locale); 
     DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); 
     dfs.setCurrencySymbol(""); 
     df.setDecimalFormatSymbols(dfs); 
     System.out.println(String.format("%5s %15s %15s", locale, format(df.format(1000)), format(df.format(1_000_000)))); 
    } 

util的方法

private static String format(String str) { 
    int index = str.lastIndexOf('\''); 
    if (index > 0) { 
     return new StringBuilder(str).replace(index, index + 1, ",").toString(); 
    } 
    return str; 
} 

輸出

it_CH  1,000.00 1'000,000.00 
fr_CH  1,000.00 1'000,000.00 
de_CH  1,000.00 1'000,000.00 

設置df.setMaximumFractionDigits(0);以除去餾分

輸出

it_CH   1,000  1'000,000 
fr_CH   1,000  1'000,000 
de_CH   1,000  1'000,000