| 1 24 package info.monitorenter.gui.chart.labelformatters; 25 26 import info.monitorenter.gui.chart.ILabelFormatter; 27 import info.monitorenter.util.Range; 28 29 import java.text.NumberFormat ; 30 import java.text.ParseException ; 31 32 33 54 public class LabelFormatterNumber extends ALabelFormatter implements ILabelFormatter { 55 56 61 private double m_cachedMinValueShift = Double.MAX_VALUE; 62 63 64 protected NumberFormat m_nf; 65 66 73 public LabelFormatterNumber(final NumberFormat numberFormat) { 74 super(); 75 if (numberFormat == null) { 76 throw new IllegalArgumentException ("Argument numberFormat must not be null."); 77 } 78 this.m_nf = numberFormat; 79 } 80 81 84 public String format(final double value) { 85 return this.m_nf.format(value); 86 } 87 88 91 public int getMaxAmountChars() { 92 int fractionDigits = 0; 94 Range range = this.getAxis().getRange(); 95 double dRange = range.getExtent(); 96 if (dRange < 1) { 97 if (dRange == 0) { 98 fractionDigits = 1; 99 } else { 100 if (dRange == 0) { 101 fractionDigits = 1; 102 } else { 103 while (dRange < 1) { 105 dRange *= 10; 106 fractionDigits++; 107 } 108 } 109 } 110 } else { 111 if (dRange < 10) { 112 fractionDigits = 2; 113 } else if (dRange < 100) { 114 fractionDigits = 1; 115 } else { 116 fractionDigits = 0; 117 } 118 } 119 120 int integerDigits = 0; 122 double max = range.getMax(); 123 double min = Math.abs(range.getMin()); 124 if (max == 0 && min == 0) { 125 integerDigits = 1; 126 } else if (max < min) { 127 while (min > 1) { 128 min /= 10; 129 integerDigits++; 130 } 131 } else { 132 while (max > 1) { 133 max /= 10; 134 integerDigits++; 135 } 136 } 137 138 if (integerDigits > this.m_nf.getMaximumIntegerDigits()) { 141 this.m_nf.setMaximumIntegerDigits(integerDigits); 142 } 143 if (fractionDigits > this.m_nf.getMaximumFractionDigits()) { 144 this.m_nf.setMaximumFractionDigits(fractionDigits); 145 } 146 return 1 + integerDigits + 1 + fractionDigits; 148 149 } 150 151 154 public double getMinimumValueShiftForChange() { 155 if (this.m_cachedMinValueShift == Double.MAX_VALUE) { 156 int fractionDigits = this.m_nf.getMaximumFractionDigits(); 157 this.m_cachedMinValueShift = 1 / Math.pow(10, fractionDigits); 158 } 159 return this.m_cachedMinValueShift; 160 } 161 162 165 public double getNextEvenValue(final double value, final boolean ceiling) { 166 double divisor = Math.pow(10, this.m_nf.getMaximumFractionDigits()); 167 if (ceiling) { 168 return Math.ceil(value * divisor) / divisor; 169 } else { 170 return Math.floor(value * divisor) / divisor; 171 } 172 } 173 174 181 NumberFormat getNumberFormat() { 182 return this.m_nf; 183 } 184 185 188 public Number parse(final String formatted) throws NumberFormatException { 189 try { 190 return this.m_nf.parse(formatted); 191 } catch (ParseException pe) { 192 throw new NumberFormatException (pe.getMessage()); 193 } 194 } 195 } 196 | Popular Tags |