格式化java中的字符串货币

时间:2014-11-10 16:59:36

标签: java string formatting decimal string-formatting

如何格式化此模式:R $ 123.456.789,12至:123456789.12?

我尝试了什么:

 String valor_minimo = mSessao.getString("filtro_pedidos_valor").substring(2);
        String valor_maximo = mSessao.getString("filtro_pedidos_valor_maior").substring(2);

        DecimalFormat dec = new DecimalFormat("#.## EUR");
        dec.setMinimumFractionDigits(2);
        String credits = dec.format(valor_maximo);

但这确实有用。

2 个答案:

答案 0 :(得分:0)

由于我的Java生锈,这有点乱,但我相信你正在寻找的是.replace方法。您可能会收到IllegalArgumentException,因为您正在尝试格式化字符串。

尝试一下,并根据需要返工:

String number = "R$123.456.789,0";
number = number.replace(".", "");
number = number.replace(",", "."); //put this second so the previous line won't wipe out your period
number = number.replace("R", "");
number = number.replace("$", "");

//two ways you can do this. either create an instance of DecimalFormat, or call it anonymously.
//instance call:
DecimalFormat df = new DecimalFormat("#.##");
//now parse the number and feed it to your decimal formatter
number = df.format(Double.parseDouble(number));

//anonymous call:
number = new DecimalFormat("#.##").format(Double.parseDouble(number));

//output test:
System.out.println(number);

希望这有帮助!

编辑更完整,更健全的答案。

答案 1 :(得分:0)

您可以使用正则表达式来清理字符串的格式

String cleanStr = inputStr.reaplaceAll("[^0-9,]","").reaplace(",",".");

所以你会得到简单的123456789.12,你可以解析它,并根据需要使用