2013-01-15 59 views
0

我有保加利亚货币像+000000027511,00。我的格式要将此格式转换为27511.00,我已经尝试过了,并使用子组合和正则表达式得到的,是否有任何模式或正则表达式做更多简化的方式?数/货币格式

实现我试过,

String currency= "+000000027511"; // "[1234]" String 
String currencyFormatted=currency.substring(1); 
System.out.println(currencyFormatted.replaceFirst("^0+(?!$)", "")); 
+0

做它的一个重要的十进制和使用'setScale' 2,或解析它作为一个float和使用'NumberFormat' – Alex

回答

1

事情是这样的:

String s = "+000000027511,00"; 
String r = s.replaceFirst("^\\+?0*", ""); 
r = r.replace(',', '.'); 
1

尝试

String s = "+000000027511,00"; 
    s = s.replace("+", "").replaceAll("^0+", "").replace(',', '.'); 
    System.out.println(s); 
2

使用Double.valueOf + DecimalFormat.format,或DecimalFormat.parse + format,或BigDecimal你可以做到这一点,因为这。

// method 1 (parsing to Float) 
    String s = "+000000027511,00".replace(",", "."); 
    Double f = Double.valueOf(s); 
    DecimalFormat df = new DecimalFormat("#########0.00"); 
    String formatted = df.format(f); 
    System.out.println(formatted); 

    // method 2 (parsing using Decimal Format) 
    s = "+000000027511,00"; 
    DecimalFormat df2 = new DecimalFormat("+#########0.00;-#########0.00"); 
    Number n = df2.parse(s); 
    df = new DecimalFormat("#########0.00"); 
    formatted = df.format(n); 
    System.out.println(formatted); 

    // method 3 (using BigDecimal) 
    BigDecimal b = new BigDecimal(s.replace(",", ".")); 
    b.setScale(2, RoundingMode.HALF_UP); 
    System.out.println(b.toPlainString()); 

将打印

27511.00 
27511.00 
27511.00 
+0

我会用'double'而不是'漂浮在99%的案件。 –

+0

是的,你是对的彼得。我也编辑了答案;) – Alex