NumberUtils { public static void correctNum(String c, TextField tf) { String s = tf.getText(); if (!digits.contains(c) && !c.equals(AppState.decimalSeparator) && s.contains(c)) { int ind = s.indexOf(c); s = s.substring(0, ind) + s.substring(ind + 1); tf.setText(s); tf.positionCaret(s.length()); } if (s.length() > 0 && s.substring(0, 1).equals(AppState.decimalSeparator)) { s = "0" + s; tf.setText(s); tf.positionCaret(s.length()); } int ind1 = s.indexOf(AppState.decimalSeparator); if (ind1 >= 0) { int ind2 = s.indexOf(AppState.decimalSeparator, ind1 + 1); if (ind2 > 0) { s = s.substring(0, ind2) + s.substring(ind2 + 1); tf.setText(s); tf.positionCaret(s.length()); } if (s.length() - ind1 > FRACTION_MAX_LENGTH) { s = s.substring(0, ind1 + FRACTION_MAX_LENGTH + 1); tf.setText(s); tf.positionCaret(s.length()); } } }  static void correctNum(String c, TextField tf); static String getCorrectNum(String s);  }
@Test public void correctNumTest() { notDigits.forEach(character -> { String text = String.valueOf(character); textField.setText(text); NumberUtils.correctNum(text, textField); }); Assert.assertEquals("", textField.getText()); textField.setText(AppState.decimalSeparator); NumberUtils.correctNum(AppState.decimalSeparator, textField); Assert.assertEquals("0" + AppState.decimalSeparator, textField.getText()); String secSepText = "123" + AppState.decimalSeparator; textField.setText(secSepText + AppState.decimalSeparator); NumberUtils.correctNum(AppState.decimalSeparator, textField); Assert.assertEquals(secSepText, textField.getText()); String additionalLengthChar = "1"; String limitLengthText = "123" + AppState.decimalSeparator + "123456789012345678"; textField.setText(limitLengthText + additionalLengthChar); NumberUtils.correctNum(additionalLengthChar, textField); Assert.assertEquals(limitLengthText, textField.getText()); }