Using Swing’s JFormattedTextField for integers is not as trivial as it should be.

Hans Muller’s Blog: Using Swing’s JFormattedTextField for integers is not as trivial as it should be.

注意,上面的範例中,  如果改為BigDecimal的話, 四捨五入會有問題…
DecimalFormat df1 = new DecimalFormat(“#,##0.00″);
        NumberFormatter nf1 = new NumberFormatter(df1) {
            public String valueToString(Object iv) throws ParseException {
                if (iv == null) {
                    return “";
                } else {
                    return super.valueToString(iv);
                }
            }
            public Object stringToValue(String text) throws ParseException {
                if (“".equals(text)) {
                    return null;
                }
                return super.stringToValue(text);
                //BigDecimal b=new BigDecimal(text).setScale(2, BigDecimal.ROUND_HALF_UP);
                //return b;
            }
        };
//        nf1.setMinimum(0);
//        nf1.setMaximum(65534);
        nf1.setValueClass(BigDecimal.class);

        DefaultFormatterFactory factory1 = new DefaultFormatterFactory(
                nf1, //Default
                nf1, //Display
                nf1);
        textAmount.setFormatterFactory(factory1);

當輸入 200.005 時, 不會變成200.01, 所以, 要自己做四捨五入, 用
amount.setScale(2, BigDecimal.ROUND_HALF_UP);
或者
 amount_USD = amount_TWD.divide(rate, 2, BigDecimal.ROUND_HALF_UP);
二個都不會有四捨五入的問題
只是, 要怎麼放在NumberFormatter內呢?
我還在想….

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

What is 4 + 14 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)