简体   繁体   中英

Limit number of decimal places of JFormattedTextField (Both UI appearance and data structure)

private JFormattedTextField getCurrencyJFormattedTextField() {
    NumberFormat format= NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(4);    
    NumberFormatter formatter= new NumberFormatter(format);
    formatter.setMinimum(0.0);
    formatter.setValueClass(Double.class);
    JFormattedTextField formattedTextField = new JFormattedTextField(formatter);
    return formattedTextField;
}

So, if I explicitly key in "1.23456789"

UI of JFormattedTextField will show "1.2346"

However, when call getValue , the returned value is 1.23456789 , not 1.23461

final double price = (Double)jFormattedTextField.getValue();

Is there any way to WYSIWYG? So that the underlying data structure will be consistence with UI display?

You have to use BigDecimal as your data type. It is specifically created for arbitrary-precision signed decimal numbers.

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