954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

limit input only two decimal

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.

onsir
Light Poster
38 posts since Apr 2007
Reputation Points: 10
Solved Threads: 1
 

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:

PoovenM
Junior Poster
151 posts since Aug 2006
Reputation Points: 56
Solved Threads: 11
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You