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

后端 未结 7 2405
梦谈多话
梦谈多话 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 10:58

    As this was the top result for a search query about forcing decimals in a NumberField, thought I would update this for those using ExtJS 4+

    The input filtering since ExtJS 4 has been delegated to a valueToRaw function, the setValue function used is actually from Ext.form.field.Text, so that's what I'm overriding below.

    I also decided to have the forcing of displaying decimals to be an option ('forcePrecision') configurable per NumberField, which means the override will look like this:

    Ext.override(Ext.form.NumberField, {
        forcePrecision : false,
    
        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, '.'));
            if (isNaN(value))
            {
              value = '';
            } else {
              value = me.forcePrecision ? value.toFixed(me.decimalPrecision) : parseFloat(value);
              value = String(value).replace(".", decimalSeparator);
            }
            return value;
        }
    });
    

    To use this in your form, you'd instantiate it like this:

    {
      xtype: 'numberfield',
      name:  'decimalsfield',
      forcePrecision: true,     #defaults to false
      decimalPrecision: 3       #defaults to 2
    }
    

    Fields not instantiated with forcePrecision: true behave exactly like the default.

提交回复
热议问题