hi,
help me, how to make limit input only two decimal, i used jformattedtext.
example : if i input more than two decimal in jformattedtext, then it can't and automatically delete by backspace.

thanks for your help.

I'm a bit confused as to what you're saying :icon_confused: But I do understand that you want to only allow real input with two decimal places. If you have a GUI then JFormattedTextField is the class you're looking for and this is how you'd use it:

NumberFormat real = NumberFormat.getNumberInstance();
real.setGroupingUsed(false);
real.setMaximumFractionDigits(2);
JFormattedTextField dataInput = new JFormattedTextField(real);

where the following imports are required:

import java.text.NumberFormat;
import javax.swing.JFormattedTextField;

What actually happens is that if you type in a number with too many decimal places, you'd see that the text field would automatically remove them. That's 'cause we .setMaximumFractionDigits(2) . We can also automatically enforce that two decimal places must be met by using real.setMinimumFractionDigits(2); and even if the user types 1, the input will change to 1.00 (after the user has changed focus to another GUI component).

I haven't actually tried to do that via a console. I would imagine that unless you read in the value, you wouldn't really know how many decimal places are there... but of course where there is Java there is a way :icon_cool:

This article has been dead for over six months. Start a new discussion instead.