01: package net.sf.jmoney.reconciliation.parser;
02:
03: import java.text.NumberFormat;
04: import java.text.ParseException;
05: import java.util.Currency;
06: import java.util.HashMap;
07: import java.util.Locale;
08:
09: public class CurrencyParser {
10: static final HashMap<String, NumberFormat> hashMap = new HashMap<String, NumberFormat>();
11:
12: static {
13: Locale[] availableLocales = Locale.getAvailableLocales();
14: for (int i = 0; i < availableLocales.length; i++) {
15: Locale locale = availableLocales[i];
16: if (locale.getCountry().length() == 2) {
17: String currencyCode = Currency.getInstance(locale)
18: .getCurrencyCode();
19: NumberFormat numberFormat = NumberFormat
20: .getCurrencyInstance(locale);
21: hashMap.put(currencyCode, numberFormat);
22: }
23: }
24: }
25:
26: public static NumberFormat getNumberFormat(Currency currency) {
27: return hashMap.get(currency.getCurrencyCode());
28: }
29:
30: /**
31: * This is a cumbersome way of converting a given string containing some amount into a long using the correct CurrencyFormat.
32: *
33: * Note : only tested for EUR
34: * Fails for USD because currency.getSymbol returns USD iso $
35: *
36: * @param amount
37: * @param currency
38: * @return
39: * @throws ParseException
40: */
41: public static long parseAmount(String amount, Currency currency)
42: throws ParseException {
43: boolean positive = amount.startsWith("+");
44: NumberFormat currencyInstance = getNumberFormat(currency);
45: Number parse = currencyInstance.parse(amount
46: .substring(positive ? 1 : 0)
47: + " " + currency.getSymbol());
48: return double2long(currency, parse);
49: }
50:
51: public static long double2long(Currency currency, Number parse) {
52: double d = parse.doubleValue();
53: d *= Math.pow(10., currency.getDefaultFractionDigits());
54: return (long) d;
55: }
56: }
|