01: /*
02: * @(#)NumberFormatHelper.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import java.text.*;
12: import java.util.*;
13: import pnuts.lang.Context;
14: import pnuts.lang.PnutsFunction;
15:
16: class NumberFormatHelper {
17:
18: private final static String FORMAT_LOCALE = "pnuts$lib$locale"
19: .intern();
20:
21: public static String formatDecimal(Number num, String fmt) {
22: DecimalFormat formatter = new DecimalFormat(fmt);
23: if (num instanceof Double) {
24: return formatter.format(((Double) num).doubleValue());
25: } else if (num instanceof Float) {
26: return formatter.format(((Float) num).doubleValue());
27: } else if (num instanceof Long) {
28: return formatter.format(((Long) num).longValue());
29: } else if (num instanceof Integer) {
30: return formatter.format(((Integer) num).longValue());
31: } else if (num instanceof Short) {
32: return formatter.format(((Short) num).longValue());
33: } else if (num instanceof Byte) {
34: return formatter.format(((Byte) num).longValue());
35: } else if (num instanceof Number) {
36: return formatter.format(((Number) num).doubleValue());
37: } else {
38: throw new IllegalArgumentException();
39: }
40: }
41:
42: public static String formatNumber(Number num, int min, int max,
43: int fmin, int fmax, Context context) {
44: NumberFormat fmt = NumberFormat
45: .getNumberInstance(getFormatLocale(context));
46: return doFormat(fmt, num, min, max, fmin, fmax);
47: }
48:
49: public static String formatCurrency(Number num, int min, int max,
50: int fmin, int fmax, Context context) {
51: NumberFormat fmt = NumberFormat
52: .getCurrencyInstance(getFormatLocale(context));
53: return doFormat(fmt, num, min, max, fmin, fmax);
54: }
55:
56: public static String formatPercent(Number num, int min, int max,
57: int fmin, int fmax, Context context) {
58: NumberFormat fmt = NumberFormat
59: .getPercentInstance(getFormatLocale(context));
60: return doFormat(fmt, num, min, max, fmin, fmax);
61: }
62:
63: static String doFormat(NumberFormat fmt, Number num, int min,
64: int max, int fmin, int fmax) {
65: setScale(fmt, min, max, fmin, fmax);
66: return fmt.format(num);
67: }
68:
69: static void setScale(NumberFormat fmt, int imin, int imax,
70: int fmin, int fmax) {
71: if (imin >= 0) {
72: fmt.setMinimumIntegerDigits(imin);
73: }
74: if (imax >= 0) {
75: fmt.setMaximumIntegerDigits(imax);
76: }
77: if (fmin >= 0) {
78: fmt.setMinimumFractionDigits(fmin);
79: }
80: if (fmax >= 0) {
81: fmt.setMaximumFractionDigits(fmax);
82: }
83: }
84:
85: static Locale getFormatLocale(Context context) {
86: Locale lc = (Locale) context.get(FORMAT_LOCALE);
87: if (lc == null) {
88: lc = locale.getLocale(context);
89: }
90: return lc;
91: }
92: }
|