Extract currency from a formatted amount

I get a formatted amount of money from a web service. It can be in different formats and use different currencies, for example.

  • $ 1.10
  • € 1,10
  • 1,10 €
  • EUR 1.10 (maybe I'm not sure if I really will come across this)

I would like to extract the currency symbol ( $ ) from it and, if possible, get the Currency (Java) object associated with it. I do not need to extract the amount, I can get it somewhere else.

+7
source share
3 answers

You can use regex to analyze your result in a web service. You must filter out all characters except numbers, periods, and spaces. Here is the regex for this:

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

The first group of the result of the match is the currency symbol (or name, for example, EUR).

Here is my example:

 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)); } } 
+3
source

You can take a look at Joda Money , he can offer a solution to your problem. Attention: this is still version 0.6

+1
source

getSymbol() method from java.util.Currency helps you get the currency symbol

0
source

All Articles