簡體   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