本文介绍了如何强制将 ExtJS NumberField 中的小数显示为特定精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 NumberField 的表单,它从 JSON 中获取 float 类型的值.如果值恰好是整数,则不显示小数位.我想始终显示 2 个小数位.有这个配置选项吗?

I have a form with a NumberField that gets values of type float from JSON. If the values happen to be whole numbers, then no decimal places are shown. I would like to show 2 decimal places at all times. Is there a config option for this?

这是我的声明:

items: [
    { 
        fieldLabel: 'Net Sales',
        name: 'netSales',
        allowBlank:false,
        decimalPrecision:2
    },

推荐答案

任一扩展 :

var myNumberField = Ext.extend(Ext.form.NumberField, {
        setValue : function(v){
            v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
            v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
            //  if you want to ensure that the values being set on the field is also forced to the required number of decimal places.
            // (not extensively tested)
            // v = isNaN(v) ? '' : this.fixPrecision(String(v).replace(".", this.decimalSeparator));
            return Ext.form.NumberField.superclass.setValue.call(this, v);
        },
        fixPrecision : function(value){
            var nan = isNaN(value);
            if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
               return nan ? '' : value;
            }
            return parseFloat(value).toFixed(this.decimalPrecision);
        }
    });

...
...

items: [new myNumberField({
        id  : 'net',
        fieldLabel: 'Net Sales',
        allowBlank:false,
        decimalPrecision:2
    }),

覆盖,这将影响您应用程序中的所有数字字段:

or override, and that will effect all numberfields in your application:

Ext.override(Ext.form.NumberField, {
    setValue : function(v){
            v = typeof v == 'number' ? v : String(v).replace(this.decimalSeparator, ".");
        v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
        return Ext.form.NumberField.superclass.setValue.call(this, v);
    },
    fixPrecision : function(value){
        var nan = isNaN(value);
        if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){
           return nan ? '' : value;
        }
        return parseFloat(value).toFixed(this.decimalPrecision);
    }
})

items: [{
        xtype   : 'numberfield',
        fieldLabel: 'Net Sales',
        allowBlank:false,
        decimalPrecision:2
    },

编辑

注意第一个 setValue 方法中的注释部分.

Notice the commented section in the first setValue method.

这篇关于如何强制将 ExtJS NumberField 中的小数显示为特定精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:55