2

我读过的关于 Java 的几乎所有内容都说不要使用浮点数或双精度数作为货币,但如果你想输入/显示具有小数位的货币值(又名正是大多数人想要做的)。

我可以使用NumberFormat.getCurrencyInstance()and NumberFormatter,但我不知道如何在不使用or的JFormattedTextField情况下让它显示小数位。我必须忽略一些简单的事情。FloatDouble

如何使我的货币字段显示$1.55,接受输入1.55并将输入存储为值为155(美分)的整数?

4

2 回答 2

2

您不能对格式化程序进行数学运算。您应该做的是让您的 pojo 的成员变量以美分保持价格。就像是:

private long priceInDollarCents;

然后你可以有一个吸气剂,它将以美元返回。就像是:

public double getPriceInDollars() {
    return (double)priceInDollarCents/100;
}

这是您将传递给格式化程序的内容。

于 2011-11-19T09:23:50.093 回答
1

你可以这样做:

在此处输入图像描述

自定义字段.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class CustomizedField extends JTextField
{
    private static final long serialVersionUID = 1L;

    public CustomizedField(int size)
    {
        super(size);
        setupFilter();
    }

    public int getCents()
    {
        String s = getText();
        System.out.println(s);
        if(s.endsWith(".")) s = s.substring(0, s.length() - 1);
        double d = Double.parseDouble(s) * 100;
        return (int) d;
    }

    private void setupFilter()
    {

        ((AbstractDocument) getDocument()).setDocumentFilter(new DocumentFilter()
        {

            @Override
            public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
            {
                check(fb, offset, text, attr);
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
            {
                check(fb, offset, text, attr);
            }

            private void check(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
            {
                StringBuilder sb = new StringBuilder();
                sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
                sb.insert(offset, text);
                if(!containsOnlyNumbers(sb.toString())) return;
                fb.insertString(offset, text, attr);
            }

            private boolean containsOnlyNumbers(String text)
            {
                Pattern pattern = Pattern.compile("([+-]{0,1})?[\\d]*.([\\d]{0,2})?");
                Matcher matcher = pattern.matcher(text);
                boolean isMatch = matcher.matches();
                return isMatch;
            }

        });
    }

}

测试.java

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Test
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Testing CustomizedField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        final CustomizedField cField = new CustomizedField(10);
        final JTextField output = new JTextField(10);
        JButton btn = new JButton("Print cents!");
        btn.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                output.setText(cField.getCents() + " cents");
            }
        });

        frame.add(cField);
        frame.add(btn);
        frame.add(output);
        frame.pack();
        frame.setVisible(true);
    }
}
于 2011-11-19T17:38:58.810 回答