i once have written this code to format the input of JFormattedTextField
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
NumberFormatter nf = new NumberFormatter(decimalFormat);
nf.setValueClass(Double.class);
nf.setAllowsInvalid(true);
nf.setOverwriteMode(false);
tfPreisIntern = new JFormattedTextField(nf);
after some time i realized the problem that occurs if the user enters for example 4,50
instead of 4.50
then the value is set to 4.00
instead of 4.50
or 4,50
. i think its an problem of my DecimalFormat
. now my question is, is it possible to have comma and point as possible decimal separator? workarounds are also okay
my method to convert the value from the JFormattedTextField
into BigDecimal
:
public static BigDecimal getBigDecimal(Object value) {
BigDecimal ret = null;
if (value != null) {
if (value instanceof BigDecimal) {
ret = (BigDecimal) value;
} else if (value instanceof String) {
ret = new BigDecimal((String) value);
} else if (value instanceof BigInteger) {
ret = new BigDecimal((BigInteger) value);
} else if (value instanceof Number) {
ret = new BigDecimal(((Number) value).doubleValue());
} else {
throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass()
+ " into a BigDecimal.");
}
}
return ret;
}
the problem with an comma i see here is that the constructor BigDecimal(string)
only allows a decimal point and not a comma
EDIT:
now trying with MaskFormatter
like this:
MaskFormatter mask = new MaskFormatter("*#.##");
mask.setPlaceholderCharacter(' ');
mask.setCommitsOnValidEdit(false);
but i can't enter values like 2.50
. this only works if i use a mask like #.##
. yet i need to have the possibility of values with 1 and 2 digits before the dot