简体   繁体   中英

How to round a JSpinner value to 2 decimals?

I am currently trying to create a JSpinner that only accepts m.netary values, ie a maximum of 2 decimals, and I tried to accomplish this using this code:

priceSpinner = new JSpinner();
SpinnerNumberModel priceSpinnerModel = new SpinnerNumberModel(
        Double.valueOf(0d), 
        Double.valueOf(0d), 
        null, 
        Double.valueOf(0.01d));
priceSpinner.setModel(priceSpinnerModel);
priceSpinner.setEditor(new JSpinner.NumberEditor(priceSpinner, "0.00"));

However, when I input a number that contains more than 2 decimals, the spinner rounds it off to 3 decimals instead. What am I doing wrong?

Works fine for me. I cannot reproduce your problem. Consider the below code.

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

public class SpinTest {

    private void createAndDisplayGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createSpinner(), BorderLayout.PAGE_START);
        frame.add(createButtons(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createButtons() {
        JPanel panel = new JPanel();
        JButton button = new JButton("Exit");
        button.addActionListener(e -> System.exit(0));
        panel.add(button);
        return panel;
    }

    private JPanel createSpinner() {
        JPanel panel = new JPanel();
        SpinnerNumberModel priceSpinnerModel = new SpinnerNumberModel(0d, 0d, null, 0.01d);
        JSpinner priceSpinner = new JSpinner(priceSpinnerModel);
        JSpinner.NumberEditor editor = new JSpinner.NumberEditor(priceSpinner, "#,##0.00");
        JFormattedTextField textField = editor.getTextField();
        textField.setColumns(12);
        priceSpinner.setEditor(editor);
        panel.add(priceSpinner);
        return panel;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new SpinTest().createAndDisplayGui());
    }
}

If I enter a number with more than two digits after the decimal point, it gets rounded to precisely two digits.

Refer to How to Use Spinners and javadoc for class java.text.DecimalFormat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM