Extract currency from formatted amount

I'm getting a formatted amount of money from a web service. It can be in different formats and using different currencies, eg

  • $ 1.10
  • € 1,10
  • 1,10 €
  • EUR 1.10 (perhaps, I'm not sure I'll actually encounter this one)
  • I would like to extract the currency symbol ( $ ) from it, and if possible get the associated Currency object (Java) from that symbol. I don't need to extract the amount, I can get that somewhere else.


    you can use a regular expression, to parse your result from the webservice. You have to filter all characters, except numbers, dots and whitespaces. Here is the regex for that:

    String regexp = "[^0-9.,s]*";
    

    The first group of the matching result is the currency symbol (or the name eg EUR).

    Here is my sample method:

    public void test() throws Exception {
        String text = "2.02 $";
        String regexp = "[^0-9.,s]*";
        Pattern p = Pattern.compile(regexp);
        Matcher m = p.matcher(text);
        while (m.find()) {
            for (int i = 0; i < m.groupCount() + 1; i++)
                LOG.info(m.group(i));
        }
    }
    

    You could have a look at Joda Money, it might offer a solution for your problem. Caution: it is still version 0.6


    java.util.Currency getSymbol()方法将帮助您获取货币符号

    链接地址: http://www.djcxy.com/p/55042.html

    上一篇: 计算在cobol四舍五入

    下一篇: 从格式化金额中提取货币