2

How would I make a java.text.NumberFormat instance that only allows positive integer numbers?

Actually, it would be nice if it only allowed from 1 and on.

Docs say that the formatting for postive/negative is divided by the ";" character, but putting nothing in the negative formatting or simply not using the ";" doesn't disables negative numbers.

These won't do it apparently:

NumberFormat nf = new DecimalFormat("#;");
// or
NumberFormat nf = new DecimalFormat("#");
// or
NumberFormat nf = new DecimalFormat("#;0");
TheStack
  • 553
  • 4
  • 12
  • What exactly do you mean with "only allows positive integer numbers"? Additionally, doc also says: "The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern." – Seelenvirtuose Oct 27 '14 at 07:27
  • See if this helps: http://stackoverflow.com/a/16227148/2115983 – Vishnu Oct 27 '14 at 07:31
  • What else is there to explain? Positive integer numbers only. I don't know how can I put it in clear terms. Maybe this article can help? http://en.wikipedia.org/wiki/Natural_number Natural numbers, without 0. That means 1, 2, 3, 4, and so on. Not -1, not 2.5. – TheStack Oct 27 '14 at 21:13
  • Its a JavaFX text field that applies the formatter. The formatter should only allow for integer numbers >= 1. – TheStack Oct 27 '14 at 21:26

2 Answers2

2

Another approach would have been to create your own NumberFormat, that uses a DecimalFormat to convert from string to integer, and then apply any limits to that resulting integer.

tbeernot
  • 2,473
  • 4
  • 24
  • 31
  • 1
    Formatting and input validation are two different concerns and should probably be handled by different classes. Good answer from @tbeernot – Guillaume Oct 28 '14 at 06:39
0

Turns out jfxtras BigDecimalField (link to Javadocs) has a method for setting the minimum value allowed. This, combined with a NumberFormat that only allows for integer numbers, allows me to make a field that only accepts integers bigger or equal than 1.

bigDecimalFld.setFormat( new DecimalFormat( "#;" ) );
bigDecimalFld.setMinValue( new BigDecimal( 1 ) );
TheStack
  • 553
  • 4
  • 12