01: package uk.org.ponder.util;
02:
03: import java.text.DecimalFormat;
04:
05: public class NumberFormatter {
06: /// The DecimalFormat used for tick labels.
07: private DecimalFormat formatter = new DecimalFormat();
08: /// The StringBuffer used to assess the form of the tick labels.
09: private StringBuffer formatstring = new StringBuffer();
10:
11: // adjust the format of the labels
12: public void adjustFormat(double stepsize, double minval,
13: double maxval) {
14: formatstring.setLength(0);
15: formatstring.append('0');
16: double furthest = Math.abs(minval) > Math.abs(maxval) ? minval
17: : maxval;
18: int figs = (int) Math.ceil(-Math.log(stepsize) / Math.log(10));
19: int bigfigs = (int) Math.ceil(-Math.log(Math.abs(furthest))
20: / Math.log(10));
21: boolean scientific = false;
22: // System.out.println("stepsize " + stepsize + " minval " + minval
23: // + " maxval " + maxval + " figs " + figs + " bigfigs " + bigfigs);
24: // bigfigs will be lower than figs
25: // positive figs represents small decimal numbers.
26: if (((bigfigs > 3) || (bigfigs < -3))) {
27: scientific = true;
28: // formatter.applyPattern("0.0E0");
29: // return;
30: }
31: if (figs > 0 || scientific)
32: formatstring.append('.');
33: int limit = 0;
34: if (figs > 0 && !scientific)
35: limit = figs;
36: if (scientific)
37: limit = figs - bigfigs;
38: for (int i = 0; i < limit; ++i) {
39: formatstring.append('0');
40: }
41: if (scientific) {
42: formatstring.append("E0");
43: }
44: formatter.applyPattern(formatstring.toString());
45: }
46:
47: public String formatQuick(double number) {
48: adjustFormat(number, 0, number);
49: return format(number);
50: }
51:
52: public String format(double number) {
53: if (number == 0.0) {
54: return "0";
55: } else
56: return formatter.format(number);
57: }
58: }
|