How do I force the display of a decimal in an ExtJS NumberField to a certain precision?

后端 未结 7 2414
梦谈多话
梦谈多话 2020-12-14 10:39

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 sho

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 11:03

    This code works great for me. It wont work with out the "ValueToRow" override in ExtJS 4.2.0.

    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);
            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;
            }
            var val = parseFloat(value).toFixed(this.decimalPrecision);
            return val;
        },
        valueToRaw: function(value) {
            var me = this,
            decimalSeparator = me.decimalSeparator;
            value = me.parseValue(value);
            value = me.fixPrecision(value);
            value = Ext.isNumber(value) ? value : parseFloat(String(value).replace(decimalSeparator, '.'));
            value = isNaN(value) ? '' : String(value).replace('.', decimalSeparator);
            return me.fixPrecision(value);
        }
    });
    
    ...
    ...
    items: [new myNumberField({
            id  : 'net',
            fieldLabel: 'Net Sales',
            allowBlank:false,
            decimalPrecision:2
        })
    

    Reference: How to keep the trailing zeros in Ext.form.field.Number ?

提交回复
热议问题