繁体   English   中英

用Java格式化字符串货币

[英]Format String currency in java

如何将以下格式设置为: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);

但这行不通。

这有点混乱,因为我的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);

希望这可以帮助!

编辑以获得更完整,更可靠的答案。

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

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

这样您将获得简单的123456789.12,您可以将其解析为两倍并按需使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM