/** Return a double parsed from the given string, possibly formatted with a "%" sign */ public static double parseDouble(String val) throws NumberFormatException, ParseException { NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor if (val.indexOf("%") == -1) { // not in percent format ! return Double.parseDouble(val); } // else it's a percent format -> parse it Number n = formatPercent.parse(val); return n.doubleValue(); }
/** * Gets the value from the text field. * * @return the value */ public double getValue() { if (getText().equals(format.format(prevValue))) return prevValue; double retValue; try { retValue = format.parse(getText()).doubleValue(); if (minValue != null && retValue < minValue.doubleValue()) { setValue(minValue.doubleValue()); return minValue.doubleValue(); } if (maxValue != null && retValue > maxValue.doubleValue()) { setValue(maxValue.doubleValue()); return maxValue.doubleValue(); } } catch (ParseException e) { Toolkit.getDefaultToolkit().beep(); setValue(prevValue); return prevValue; } return retValue; }
/** * @return a double parsed from the value associated with the given key in the given Properties. * returns "def" in key wasn't found, or if a parsing error occured. If "value" contains a "%" * sign, we use a <code>NumberFormat.getPercentInstance</code> to convert it to a double. */ public static double parseProperty(Properties preferences, String key, double def) { NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor String val = preferences.getProperty(key); if (val == null) return def; if (val.indexOf("%") == -1) { // not in percent format ! try { return Double.parseDouble(val); } catch (NumberFormatException nfe) { nfe.printStackTrace(); return def; } } // else it's a percent format -> parse it try { Number n = formatPercent.parse(val); return n.doubleValue(); } catch (ParseException ex) { ex.printStackTrace(); return def; } }