KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > math > Money


1 /*
2   Copyright (C) 2006 Know Gate S.L. All rights reserved.
3                       C/Oña, 107 1º2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.math;
34
35 import java.math.BigInteger JavaDoc;
36 import java.math.BigDecimal JavaDoc;
37
38 import java.text.DecimalFormat JavaDoc;
39 import java.text.FieldPosition JavaDoc;
40 import java.text.NumberFormat JavaDoc;
41
42 import java.util.Currency JavaDoc;
43
44 import com.knowgate.misc.Gadgets;
45 import java.util.Locale JavaDoc;
46
47 import com.knowgate.misc.Gadgets;
48
49 /**
50  * <p>Combination of BigDecimal with Currency Sign</p>
51  * This class handles money amounts that include a currency sign
52  * @author Sergio Montoro Ten
53  * @version 1.0
54  */

55 public class Money extends BigDecimal JavaDoc {
56
57   private static final DecimalFormat JavaDoc FMT2 = new DecimalFormat JavaDoc("#0.00");
58   private static final FieldPosition JavaDoc FRAC = new FieldPosition JavaDoc(NumberFormat.FRACTION_FIELD);
59
60   private CurrencyCode oCurrCode;
61
62   // ---------------------------------------------------------------------------
63

64   private Money(String JavaDoc sVal) throws UnsupportedOperationException JavaDoc {
65     super(sVal);
66     throw new UnsupportedOperationException JavaDoc("Money(String) is not an allowed constructor");
67   }
68
69   // ---------------------------------------------------------------------------
70

71   public Money(Money oVal) {
72     super(((BigDecimal JavaDoc) oVal).toString());
73     oCurrCode = oVal.oCurrCode;
74   }
75
76   // ---------------------------------------------------------------------------
77

78   /**
79    * Constructor
80    * @param sVal String Numeric value in US decimal format (using dot as decimal delimiter)
81    * @param oCur CurrencyCode
82    * @throws NumberFormatException
83    */

84   public Money(String JavaDoc sVal, CurrencyCode oCur) throws NumberFormatException JavaDoc {
85     super(sVal);
86     oCurrCode = oCur;
87   }
88
89   // ---------------------------------------------------------------------------
90

91   /**
92    * Constructor
93    * @param sVal String Numeric value in US decimal format (using dot as decimal delimiter)
94    * @param sCur String Currency alphanumeric code {"USD", "EUR", etc.}
95    * @throws NumberFormatException
96    * @throws IllegalArgumentException
97    */

98   public Money(String JavaDoc sVal, String JavaDoc sCur)
99     throws NumberFormatException JavaDoc, IllegalArgumentException JavaDoc {
100     super(sVal);
101     oCurrCode = CurrencyCode.currencyCodeFor(sCur);
102     if (null==oCurrCode) throw new IllegalArgumentException JavaDoc("Money() "+sCur+" is not a legal currency alphanumeric code");
103     oCurrCode = CurrencyCode.currencyCodeFor(sCur);
104   }
105
106   // ---------------------------------------------------------------------------
107

108   /**
109    * Constructor
110    * @param dVal double
111    * @param oCur CurrencyCode
112    */

113   public Money(double dVal, CurrencyCode oCur) {
114     super(dVal);
115     oCurrCode = oCur;
116   }
117
118   // ---------------------------------------------------------------------------
119

120   /**
121    * Constructor
122    * @param dVal double
123    * @param sCur String Currency alphanumeric code {"USD", "EUR", etc.}
124    * @throws IllegalArgumentException
125    */

126   public Money(double dVal, String JavaDoc sCur) throws IllegalArgumentException JavaDoc {
127     super(dVal);
128     oCurrCode = CurrencyCode.currencyCodeFor(sCur);
129   }
130
131   // ---------------------------------------------------------------------------
132

133   public Money(BigDecimal JavaDoc oVal, CurrencyCode oCur) {
134     super(oVal.toString());
135     oCurrCode = oCur;
136   }
137
138   // ---------------------------------------------------------------------------
139

140   public Money(BigDecimal JavaDoc oVal, String JavaDoc sCur) {
141     super(oVal.toString());
142     oCurrCode = CurrencyCode.currencyCodeFor(sCur);
143   }
144
145   // ---------------------------------------------------------------------------
146

147   public Money(BigInteger JavaDoc oVal, CurrencyCode oCur) {
148     super(oVal);
149     oCurrCode = oCur;
150   }
151
152   // ---------------------------------------------------------------------------
153

154   public Money(BigInteger JavaDoc oVal, String JavaDoc sCur) {
155     super(oVal);
156     oCurrCode = CurrencyCode.currencyCodeFor(sCur);
157   }
158
159   // ---------------------------------------------------------------------------
160

161   public CurrencyCode currencyCode() {
162     return oCurrCode;
163   }
164
165   // ---------------------------------------------------------------------------
166

167   public static boolean isMoney (String JavaDoc sVal) {
168     if (sVal==null) return false;
169     if (sVal.length()==0) return false;
170     String JavaDoc sAmount = sVal.toUpperCase();
171     int iDot = sAmount.indexOf('.');
172     int iCom = sAmount.indexOf(',');
173     if (iDot!=0 && iCom!=0) {
174       if (iDot>iCom) {
175         Gadgets.removeChar(sAmount,',');
176       } else {
177         Gadgets.removeChar(sAmount,'.');
178       }
179     } // fi
180
sAmount = sAmount.replace(',','.');
181     sAmount = Gadgets.removeChars(sAmount, "€$£¤¢¥#ƒ& ABCDEFGHIJKLMNOPQRSZUVWXYZ");
182     boolean bMatch = false;
183     try {
184       bMatch = Gadgets.matches(sAmount, "([0-9]+)|([0-9]+.[0-9]+)");
185     } catch (org.apache.oro.text.regex.MalformedPatternException neverthrown) {}
186     return bMatch;
187   } // isMoney
188

189   // ---------------------------------------------------------------------------
190

191   public static Money parse(String JavaDoc sVal)
192     throws NullPointerException JavaDoc,IllegalArgumentException JavaDoc,NumberFormatException JavaDoc {
193     int iDot, iCom;
194     CurrencyCode oCur = null;
195     String JavaDoc sAmount;
196
197     if (null==sVal) throw new NullPointerException JavaDoc("Money.parse() argument cannot be null");
198     if (sVal.length()==0) throw new IllegalArgumentException JavaDoc("Money.parse() argument cannot be an empty string");
199
200     sAmount = sVal.toUpperCase();
201     if (sAmount.indexOf("EUR")>=0 || sAmount.indexOf("€")>=0 || sAmount.indexOf("&euro;")>=0)
202       oCur = CurrencyCode.EUR;
203     else if (sAmount.indexOf("USD")>=0 || sAmount.indexOf("$")>=0)
204       oCur = CurrencyCode.USD;
205     else if (sAmount.indexOf("GBP")>=0 || sAmount.indexOf("£")>=0)
206       oCur = CurrencyCode.GBP;
207     else if (sAmount.indexOf("JPY")>=0 || sAmount.indexOf("YEN")>=0 || sAmount.indexOf("¥")>=0)
208       oCur = CurrencyCode.JPY;
209     else if (sAmount.indexOf("CNY")>=0 || sAmount.indexOf("YUAN")>=0)
210       oCur = CurrencyCode.CNY;
211
212     iDot = sAmount.indexOf('.');
213     iCom = sAmount.indexOf(',');
214
215     if (iDot!=0 && iCom!=0) {
216       if (iDot>iCom) {
217         Gadgets.removeChar(sAmount,',');
218       } else {
219         Gadgets.removeChar(sAmount,'.');
220       }
221     } // fi
222

223     sAmount = sAmount.replace(',','.');
224     sAmount = Gadgets.removeChars(sAmount, "€$£¤¢¥#ƒ& ABCDEFGHIJKLMNOPQRSZUVWXYZ");
225
226     return new Money(sAmount, oCur);
227   } // parse
228

229   // ---------------------------------------------------------------------------
230

231   /**
232    * Rounds a BigDecimal value to two decimals
233    * @return BigDecimal
234    */

235   public Money round2 () {
236     StringBuffer JavaDoc oBuffer = new StringBuffer JavaDoc();
237     FMT2.format(doubleValue(), oBuffer, FRAC);
238     return new Money (oBuffer.toString(), oCurrCode);
239   }
240
241   // ---------------------------------------------------------------------------
242

243   /**
244    * <p>Convert <b>this</b> money to another currency</p>
245    * @param oTarget Target CurrencyCode
246    * @param oRatio BigDecimal Conversion ratio
247    * @return Money if <b>this</b> CurrencyCode is the same as oTarget
248    * then <b>this</b> is returned without any modification,
249    * if if <b>this</b> CurrencyCode is different from oTarget
250    * then the returned value is <b>this</b> multiplied by oRatio.
251    * @throws NullPointerException if oTarget is <b>null</b>
252    */

253   public Money convertTo (CurrencyCode oTarget, BigDecimal JavaDoc oRatio)
254     throws NullPointerException JavaDoc {
255
256     Money oNewVal;
257
258     if (oTarget==null) throw new NullPointerException JavaDoc("Money.convertTo() target currency cannot be null");
259
260     if (oCurrCode!=null) {
261       if (oCurrCode.equals(oTarget))
262         oNewVal = this;
263       else
264         oNewVal = new Money(multiply(oRatio), oTarget);
265     } else {
266       oNewVal = new Money(multiply(oRatio), oTarget);
267     }
268     return oNewVal;
269   } // convertTo
270

271   // ---------------------------------------------------------------------------
272

273  /**
274   * Format a BigDecimal as a String following the rules for an specific language and country
275   * @param sLanguage String ISO-639 two letter language code
276   * @param sCountry String ISO-3166 two leter country code
277   * @return String
278   */

279
280  public String JavaDoc format (String JavaDoc sLanguage, String JavaDoc sCountry) {
281
282     Locale JavaDoc oLoc;
283     if (null==sCountry) sCountry = oCurrCode.countryCode();
284
285     if (null!=sLanguage && null!=sCountry)
286       oLoc = new Locale JavaDoc(sLanguage,sCountry);
287     else if (null!=sLanguage)
288       oLoc = new Locale JavaDoc(sLanguage);
289     else
290       oLoc = Locale.getDefault();
291     NumberFormat JavaDoc oFmtC = NumberFormat.getCurrencyInstance(oLoc);
292     oFmtC.setCurrency(currencyCode().currency());
293     return oFmtC.format(doubleValue());
294   } // format
295

296   // ---------------------------------------------------------------------------
297

298   public String JavaDoc toString () {
299     if (oCurrCode==null)
300       return super.toString();
301     else
302      return super.toString()+" "+oCurrCode.alphaCode();
303   }
304
305   // ---------------------------------------------------------------------------
306

307 }
308
Popular Tags