简体   繁体   English

限制JFormattedTextField的小数位数(UI外观和数据结构)

[英]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" 因此,如果我明确输入“ 1.23456789”

UI of JFormattedTextField will show "1.2346" JFormattedTextField的用户界面将显示“ 1.2346”

However, when call getValue , the returned value is 1.23456789 , not 1.23461 然而,打电话的时候getValue ,返回的值是1.23456789 ,而不是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? 这样底层数据结构将与UI显示保持一致?

You have to use BigDecimal as your data type. 您必须使用BigDecimal作为数据类型。 It is specifically created for arbitrary-precision signed decimal numbers. 它是专为任意精度的带符号十进制数字创建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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