I need to show numbers in jTable with exact 2 decimal places. To accomplish this I have created a custom cell editor as:
public class NumberCellEditor extend
Try
DecimalFormat numberFormat = new DecimalFormat("\\d*([\\.,\\,]\\d{0,2})?");
Just change #,###,###,##0.00
with #.###.###.##0,00
for example
import java.text.NumberFormat;
import java.math.RoundingMode;
import javax.swing.table.DefaultTableCellRenderer;
public class SubstDouble2DecimalRenderer extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private int precision = 0;
private Number numberValue;
private NumberFormat nf;
public SubstDouble2DecimalRenderer(int p_precision) {
super();
setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
precision = p_precision;
nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(p_precision);
nf.setMaximumFractionDigits(p_precision);
nf.setRoundingMode(RoundingMode.HALF_UP);
}
public SubstDouble2DecimalRenderer() {
super();
setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
nf.setRoundingMode(RoundingMode.HALF_UP);
}
@Override
public void setValue(Object value) {
if ((value != null) && (value instanceof Number)) {
numberValue = (Number) value;
value = nf.format(numberValue.doubleValue());
}
super.setValue(value);
}
}
Use the locale to your advantage:
//Locale myLocale = Locale.GERMANY; //... or better, the current Locale
Locale myLocale = Locale.getDefault(); // better still
NumberFormat numberFormatB = NumberFormat.getInstance(myLocale);
numberFormatB.setMaximumFractionDigits(2);
numberFormatB.setMinimumFractionDigits(2);
numberFormatB.setMinimumIntegerDigits(1);
edit.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
new NumberFormatter(numberFormatB)));