2013-04-09 75 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); 

我感到心脏写,所以写回,如果遇到问题