Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should extend <code>NumberFormatter</code> rather than <code>NumberFormat</code> and override <code>stringToValue</code> so that it verifies that when the string is parsed you get back the original value:</p> <pre><code>class StrictNumberFormatter extends javax.swing.text.NumberFormatter { @Override public Object stringToValue(String text) throws ParseException { Object parsedValue = super.stringToValue(text); String expectedText = super.valueToString(parsedValue); if (! super.stringToValue(expectedText).equals(parsedValue)) { throw new ParseException("Rounding occurred", 0); } return parsedValue; } public StrictNumberFormatter(NumberFormat nf) { super(nf); } } NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); JFormattedTextField.AbstractFormatter formatter = new StrictNumberFormatter(nf); final JFormattedTextField ftf = new JFormattedTextField(formatter); ftf.setValue(new BigDecimal("1234.50")); </code></pre> <p>This formatter will reject the new text if the values before and after rounding do not match.</p> <p>Note: this compares the <em>values</em>, not the strings. It will tolerate changes like removing grouping characters (<code>"$1,000"</code> => <code>"$1000"</code>) and trailing zeros (<code>"$1.20"</code> => <code>"$1.2"</code>). Basically if the <code>NumberFormat</code> returns the same value then it is acceptable. But any restrictions imposed by the <code>NumberFormat</code> still apply, e.g. you must not remove the currency symbol or insert leading spaces etc.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload