01: package com.jat.util;
02:
03: import java.math.BigDecimal;
04: import java.text.DecimalFormat;
05: import java.text.NumberFormat;
06: import java.util.Locale;
07:
08: /**
09: * <p>Title: JAT</p>
10: * <p>Description: </p>
11: * <p>Copyright: Copyright (c) 2004 -2005 Stefano Fratini (stefano.fratini@gmail.com)</p>
12: * <p>Distributed under the terms of the GNU Lesser General Public License, v2.1 or later</p>
13: * @author stf
14: * @version 1.1
15: */
16:
17: public class PriceUtil {
18:
19: public PriceUtil(int fractionDigits, Locale locale) {
20: this .setFractionDigits(fractionDigits);
21: this .setLocale(locale);
22: }
23:
24: public void setFractionDigits(int fractionDigits) {
25: this .fractionDigits = fractionDigits;
26: }
27:
28: public void setLocale(Locale locale) {
29: this .locale = locale;
30: }
31:
32: public String formatPrice(String price) {
33: String p = new String(price);
34: BigDecimal bd = new BigDecimal(p);
35: bd = bd
36: .divide(new BigDecimal(1), this .fractionDigits,
37: rounding);
38: return formatLocalePrice(bd);
39: }
40:
41: public String formatPrice(Object price) {
42: return formatPrice("" + price);
43: }
44:
45: public int getRoundingMethod() {
46: return this .rounding;
47: }
48:
49: public void setRoundingMathod(int round) throws Exception {
50: try {
51: BigDecimal bd = new BigDecimal("10");
52: bd = bd.divide(new BigDecimal(3), 2, round);
53: } catch (Exception ex) {
54: throw new Exception(
55: "Malformed BigDecimal rounding method (" + round
56: + "): " + ex);
57: }
58: this .rounding = round;
59: }
60:
61: private String formatLocalePrice(Object price) {
62: if (dFormat == null) {
63: dFormat = (DecimalFormat) NumberFormat.getInstance(locale);
64: dFormat.setMaximumFractionDigits(this .fractionDigits);
65: dFormat.setMinimumFractionDigits(this .fractionDigits);
66: }
67: return dFormat.format(price);
68: }
69:
70: private DecimalFormat dFormat = null;
71: private int fractionDigits;
72: private Locale locale;
73: private int rounding = BigDecimal.ROUND_HALF_UP;
74:
75: }
|