Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, e.g.

  • $ 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.

like image 324
Bart van Heukelom Avatar asked Sep 28 '11 12:09

Bart van Heukelom


People also ask

How do I extract currency format in Excel?

Extract the text string representing the full custom number format using the [cell]. numberformat property (gives something like “CAD” #,##0.00;”CAD” -#,##0.00″) Trim the text string (MID) to remove the everything except the currency code. Return the currency code as a string to the spreadsheet.

How will you format a value to currency?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.

How do I extract currency from Google Sheets?

Here's how to convert currency in Google Sheets to get the exchange rate of dollars to the three currencies in column B: Select the first cell of the column where you want the results to appear (C2). Type the formula: =GOOGLEFINANCE(“CURRENCY:USDINR”) Press the return key.


1 Answers

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 e.g. 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));
    }
}
like image 142
ben_muc Avatar answered Sep 18 '22 20:09

ben_muc