2013-04-09 76 views
0

格式化數字字符串我具有表示數字的字符串(例如,1234.56)和表示格式的字符串,並需要格式化數字串格式字符串。兩個字符串中給出。根據格式字符串

更好underdstanding一些代碼:

public static void main(String[] args) { 
    String number = "1000.0"; 
    formatNumber(number, "1,234.56"); //Should be 1,000.00 
    formatNumber(number, "1 234.56"); //Should be 1 000.00 
    formatNumber(number, "1234,56"); //Should be 1000,00 
} 

public static String formatNumber(String number, String format) { 
    return ??? 
} 

最新最好的方式來實現這一目標?

感謝 保羅

+1

使用十進制格式,在這個線程[鏈接] [1] [1] menthioned:HTTP:/ /stackoverflow.com/questions/6376226/how-to-convert-a-formatted-string-to-float-in-java-with-different-locales – muneebShabbir 2013-04-09 09:14:09

回答

2

這三行應該做的。

String pattern = format.replaceAll("\\d", "#"); 
DecimalFormat myFormatter = new DecimalFormat(pattern); 
return myFormatter.format(value); 

我感到心臟寫,所以寫回,如果遇到問題